UnknownHostException异常

测试环境,用http发送get请求文件服务器下载文件,显示找不到UnknownHostException,但是用a标签href可以直接访问下载图片说明
图片说明

3个回答

//链接url下载图片
    public static void downloadPicture(String urlList,String path) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());


            FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();


            byte[] buffer = new byte[1024];
            int length;


            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

域名不能解析,或者dns不稳定。设置dns为另一个,比如8.8.8.8看看

你域名要加http://吧

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
java UnknownHostException异常
如下错误 ``` java.net.UnknownHostException: apis.baidu.com ``` 求解答呀!!
java 异常java.net.UnknownHostException
package app21; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; public class SocketTest1 { public static void main(String[] args) { String host = "www.baidu.com"; String protocol = "https"; try { Socket socket = new Socket(protocol + "://" + host, 80); OutputStream os = socket.getOutputStream(); boolean autoflush = true; PrintWriter out = new PrintWriter(os, autoflush); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); // 将一个HTTP请求发送到Web服务器 out.println("GET / HTTP/1.1"); out.println("Host: " + host + ":80"); out.println("Connection: Close"); out.println(); // 读取响应信息 boolean loop = true; StringBuilder sb = new StringBuilder(8096); while (loop) { if (in.ready()) { int i = 0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } } // 将响应信息显示到out控制台 System.out.println(sb.toString()); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } 异常信息: java.net.UnknownHostException: https://www.baidu.com at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at java.net.Socket.connect(Socket.java:538) at java.net.Socket.<init>(Socket.java:434) at java.net.Socket.<init>(Socket.java:211) at app21.SocketTest1.main(SocketTest1.java:16)
Docker 中java程序对外请求,报错:Root Cause exception : java.net.UnknownHostException
1、在虚拟机中centos7 系统中,安装了Docker环境,想实现在docker中运行 “java -jar test.jar”,其中test.jar的main函数中会对外发起http请求,url=“http://plm.xxx.com:9091/xxx”,初始启动运行镜像文件就报错: ``` java.net.UnknownHostException: PLM at java.net.Inet4AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901 ``` 2、我配置的dockfile 文件为: ``` From centos MAINTAINER liubin ADD test.jar test.jar ADD jdk-7u80-linux-x64.tar.gz /home/jdk/ ENV JAVA_HOME /home/jdk/jdk1.7.0_80 ENV PATH $JAVA_HOME/bin:$PATH ENV CLASSPATH=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar ENTRYPOINT ["java","-jar","test.jar"] ``` 3、直接尝试在centos环境中运行java -jar test.jar不会报异常,我的/etc/hosts文件中配置了PLM相关地址 ``` 127.0.0.1 node1 localhost ::1 node1 localhost 192.168.2.18 plm.xxx.com plmapp PLM #与请求地址相关的域名 192.168.2.113 ode1 192.168.2.128 AAASPLMIFS ``` 4、我的问题是docker 中运行java程序报这个UnknownHostException,是不是需要在Dockerfile中配置其它内容。 不好意思,最近没有积分呀、
微信企业号调用接口时java.net.UnknownHostException: qyapi.weixin.qq.com
企业号开发时,偶尔出现这种异常,过一段时间又好使了,不知道是代码问题?网络问题?
百度API调用异常,谢谢
在调用百度API实现“将地址解析为对应经纬度”时提示一下异常,求解决方案 java.net.UnknownHostException: api.map.baidu.com at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.<init>(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.URL.openStream(Unknown Source) at change.LatitudeUtils.getGeocoderLatitude(LatitudeUtils.java:27) at change.LatitudeUtils.main(LatitudeUtils.java:62) java.lang.NullPointerException at change.LatitudeUtils.getGeocoderLatitude(LatitudeUtils.java:52) at change.LatitudeUtils.main(LatitudeUtils.java:62)
求大神帮忙解决 Android项目java空指针异常问题 真的很急 - -
新手小白参考网上教程学习的socket使用,代码几乎雷同老师写的就可以运行我的就会出问题,connect()方法正确可用,但是send()方法不能用,会提示如图空指针异常,但是我真的找不到是哪里的问题,求大神指点。困扰两天了 茶不思饭不想。(由于提问字数问题导包部分代码没有粘过来) 我用Broadcast在一个activity中监听到操作后广播消息过来然后触发java类里面的方法,触发到connect()就可以运行,但是触发send()方法就报错空指针异常。大神指点,拜托了。 public class Sockets extends BroadcastReceiver{ Socket socket= null; BufferedWriter writer= null; BufferedReader reader = null; PrintWriter testPrintWriter = null; String Massage = null; public void connect(){ AsyncTask<Void,String,Void> read = new AsyncTask<Void, String, Void>() { @Override protected Void doInBackground(Void... arg0) { try { socket = new Socket("10.10.74.75",59671); writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); publishProgress("@success"); } catch (UnknownHostException e1) { System.out.println("连接失败!"); } catch (IOException e1) { System.out.println("连接失败!"); } try { String line; while ((line = reader.readLine())!=null) { publishProgress(line); } } catch (Exception e) { } return null; } @Override protected void onProgressUpdate(String... values) { if (values[0].equals("@success")) { System.out.println(">>>>>>>>>>>>>>>"+values[0]); } Massage = values[0]; super.onProgressUpdate(values); } }; read.execute(); } public void send(String massageSend) { try { writer.write(massageSend+"\n");//+ writer.flush(); } catch (IOException e) { e.printStackTrace(); } } @Override public void onReceive(Context arg0, Intent arg1) { connect(); send(arg1.getStringExtra("massage")); } }![图片说明](https://img-ask.csdn.net/upload/201509/16/1442397756_87558.jpg)
java 简单的服务器端与多客户端通信异常的问题
# 服务器端代码 package service; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; import java.util.zip.InflaterInputStream; public class Server { public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket ss = null; try { System.out.println("服务器已启动,等待客户端连接。。。"); ss = new ServerSocket(8888); while (true) { Socket s = ss.accept(); new serverthread(s).start(); s.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class serverthread extends Thread { Socket s = null; String str; public serverthread(Socket socket) { super(); this.s = socket; System.out.println("一个客户端已经连接上"); } PrintStream out=null; BufferedReader in =null; @Override public void run() { // TODO Auto-generated method stub try { System.out.println(s.getLocalPort()); out=new PrintStream(s.getOutputStream(), true); in=new BufferedReader(new InputStreamReader(s.getInputStream()));//获取客户端套接字输入输出流 str=in.readLine(); System.out.println("客户端用户名"+str); if (str.equals("JSIT")) { out.println("用户名正确"); }else out.println("用户名不存在"); } catch (IOException e) { // TODO Auto-generated catch block } } } # 客户端代码 package client; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; public class Clint2 { public static void main(String[] args) { // TODO Auto-generated method stub try { Socket s=new Socket("127.0.0.1", 8888); PrintStream out=new PrintStream(s.getOutputStream()); BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); System.out.print("用户名:"); String str=stdin.readLine(); out.println(str); System.out.println(in.readLine()); in.close(); out.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 我先运行了服务端,再运行客户端时会报socket is closed的异常,是什么原因?
InputStream对象无法获取Urlconnection对象.getInputSteam的值
虽然没有错不报错,但是却抓不到数据,同时异常里可以捕抓到IO异常,但是没有提示 ``` @Override protected Bitmap doInBackground(String... params) { String url=params[0]; Bitmap bitmap=null; URLConnection connection; InputStream is; //通过URL.openConnection方法获得一个URLConnection对象 try { URL myurl = new URL(url); connection=myurl.openConnection(); connection.connect(); is=connection.getInputStream(); //包装一下 //BufferedInputStream bis=new BufferedInputStream(is); //将一个输入流解析为一个BitMap对象 bitmap=BitmapFactory.decodeStream(is); //关闭输入流 is.close(); //bis.close(); } catch (MalformedURLException e) { Log.i("info", "MalformedURLException"); e.printStackTrace(); } catch (IOException e) { Log.i("info", "IOException:"+e.toString()); e.printStackTrace(); } return bitmap; } ``` ``` private String URL = "http://image.sinajs.cn/newchart/monthly/n/sh601003.gif"; ``` 刚刚调试获得一个异常 IOException:java.net.UnknownHostException: Unable to resolve host "image.sinajs.cn": No address associated with hostname
jdbc连接hive查询报错:local host is: (unknown);
**hive sql:** select row_number() over (order by trademark) id,* from iot.dr_ps_20171228 limit 1 **报错信息:** java.net.UnknownHostException: Invalid host name: local host is: (unknown); destination host is: "xhw367":8032; java.net.UnknownHostException; For more details see: http://wiki.apache.org/hadoop/UnknownHost **补充:** 1、local host不是我分着打的,这是异常信息抛出来的。 2、只有在用hive聚合函数才会出现这个问题,普通的select不会出现。 **已解决,详见:http://blog.csdn.net/tanglei6636/article/details/79161695**
JAVA的Socket为什么会自动关闭。跪了,求解
问题描述: 这里有一个服务器和一个带图形界面客户端。当的用户账号密码正确时,客户端会向服务器提出连接请求,也就是new Sicket(..., ...); 可是为什么客户端这个Socket会在成功连接7秒左右自动关闭。 我判断客户端的Socket已经关闭的原因有两个。 1.客户端的socket不停调用s.sendUrgentData方法,但在运行7秒左右时会抛出异常。 2 服务器一直在等待客户端的消息,但是在运行7秒左右服务器却抛出connection reset异常,在抛异常之前客户端可以正常发送数据,异常之后不能再发送了,在百度上知道这是因为发送方(也就是客户端)的socket已经关闭,而接收方还在等待接受而抛出的异常。 相关代码: // 客户端代码 public class LoginFrame extends JFrame { private Socket s ; if (log()) { // log是连接数据库的函数,会返回boolean表示用户名密码对不对 s = Client.requst(nameTF.getText()); // 为s赋值,将返回的Socket保存在s中, 类的静态方法requst } else { System.out.println("登陆失败"); } } // 主函数 public static void main(String[] args) throws InterruptedException { LoginFrame f = new LoginFrame(); Thread.sleep(2000);// 为了给输入用户名和密码时间 while (true) { try { f.s.sendUrgentData(0xFF); System.out.println("发送成功"); } catch (IOException e) { System.out.println("因发送心跳包出现异常" + e.getMessage()); break } } } // 客户端的连接请求代码 public class Client { public static Socket requst(String name) { Socket s = null; try { // 发出连接请求 s = new Socket("127.0.0.1", 8888); PrintWriter writer = new PrintWriter(s.getOutputStream()); // 告诉服务器是谁刚刚连接 writer.write(name + "\n"); writer.flush(); } catch (UnknownHostException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } return s; } 相关截图 客户端异常 ![图片说明](https://img-ask.csdn.net/upload/201906/16/1560659211_996428.jpg) 服务器异常(提问时,异常变成这个,但之前都是Connection reset) ![图片说明](https://img-ask.csdn.net/upload/201906/16/1560659224_174504.jpg) 请各位朋友帮忙了。 这次是JAVA课程设计,但老师并没有讲Socket,Socket的一些细节我也不清楚。所以拜托了帮我找找Bug。 ---------------------------------------------------------------------- 各位我实在是充不起C币。 要是问题解决了, 你支付宝二维码或者微信发过来, 我给你6块行不行。 拜托了,帮帮我吧。
重金求解,为什么我接收不到socket服务端返回的信息,代码如下,这个logger.debug("result:"result)为什么总是空,确认了服务端的确返回到了socket,怎样才能正确从socket取到值呢?
这是socket客户端代码 ``` import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class Client extends Thread { Socket socket = null; public String result = ""; public String in = ""; public Client(String host, int port, String in) { try { in = new String(in.getBytes(),"GBK"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } this.in = in; try { socket = new Socket(host, port); socket.setSoTimeout(1000); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // public void shutDown() throws IOException { // if (socket != null) { // synchronized (socket) { // socket.close(); // } // } // System.out.println("StopClose.shutDown() complete"); // } @Override public void run() { new sendMessThread().start(); super.run(); try { InputStream s = socket.getInputStream(); byte[] buf = new byte[1024]; int len = 0; while ((len = s.read(buf)) != -1) { System.out.println(new String(buf, 0, len)); } } catch (IOException e) { e.printStackTrace(); } } class sendMessThread extends Thread{ @Override public void run() { super.run(); Scanner scanner=null; OutputStream os= null; try { scanner=new Scanner(System.in); os= socket.getOutputStream(); // String in; // do { // in=scanner.next(); // os.write((""+in).getBytes()); // os.flush(); // } while (!in.equals("bye")); for(int i =0;i<1;i++) { os.write((""+in).getBytes()); os.flush(); } BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK")); String str = ""; System.out.println("RESULT AS FOLLOWING:"); while ((str = rd.readLine()) != null) { System.out.println(str); } // str = rd.readLine(); Client.this.result = str; System.out.println("Client.this.result:"+Client.this.result); rd.close(); } catch (IOException e) { e.printStackTrace(); } scanner.close(); try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { // Client clientTest=new Client("88.6.13.66", 13000); // Client clientTest=new Client("127.0.0.1", 1234,""); // clientTest.start(); } } ``` 这是调用的代码 ``` import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.sql.Connection; import java.sql.Types; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; public class FaceCheckManage { private final static String DB_ALIAS = "ALIAS";//数据源 private static final String TRXZONE = "trxZone";//输入|地区号 private static final String TYPE = "type";//输入|操作类型 add-注册 check-识别 del-删除 private static final String IMG = "img";//输入|人脸数据 private static final String ID = "id";//输入|编号 private static final String VALUE = "VALUE";//输出|转发数据 public String process(IWFEngine engine, WFActivity activity, WFData wfd, String wfName) throws ParamNotExistException, com.zjft.bpe.stdlib.exception.UnrecognizedScopeException { BizDataModule dm = wfd.getDataModule(); ZjLogger logger = LoggerUtil.getLog(dm.getChannelId(), dm.getTxCode()); ModuleUtil moduleUtil = new ModuleUtil(wfd, wfd.getDataModule(), activity, logger); String trxZone = moduleUtil.getParamValue(TRXZONE); logger.debug("trxZone:"+trxZone); String type = moduleUtil.getParamValue(TYPE); String imgBase64 = moduleUtil.getParamValue(IMG); String id = moduleUtil.getParamValue(ID); Connection conn = wfd.getTxConnection(moduleUtil.getParamValue(DB_ALIAS)); try { /*是否已注册*/ boolean registedFlag = isRegisted(id, conn, logger); if("add".equals(type)&&registedFlag==true) { CommonUtil.setResponseMsg("FFFFF", "用户已注册,请先删除人脸数据", moduleUtil); return "fail"; }else if(("check".equals(type)||"del".equals(type))&&registedFlag==false) { CommonUtil.setResponseMsg("FFFFF", "用户人脸数据未注册", moduleUtil); return "fail"; } } catch (Exception e) { logger.error("查询是否已注册发生异常",e); CommonUtil.setResponseMsg("FFFFF", "查询是否已注册发生异常", moduleUtil); return "fail"; } JSONObject sysParams = null;//系统参数列表 try { //获取人脸识别配置参数 sysParams = getSysParam(type,conn, logger); }catch (TradeException e) { CommonUtil.setResponseMsg("FFFFF", e.getMessage(), moduleUtil); return "fail"; } catch (Exception e) { logger.error("查询人脸识别系统参数发生异常",e); CommonUtil.setResponseMsg("FFFFF", "查询人脸识别系统参数发生异常", moduleUtil); return "fail"; } String ip = sysParams.getString("ip"); String url =sysParams.getString("url"); //组参数 JSONObject paramMap = new JSONObject(); if("add".equals(type)) { paramMap.put("trxZone", trxZone); paramMap.put("programName", "e"); paramMap.put("id", id); paramMap.put("img1", imgBase64); paramMap.put("imgFace1", "50,60,100,120"); paramMap.put("hack1", 1); paramMap.put("customerAgreement", 1); String trxString = "10032"; String jsonString = paramMap.toJSONString(); int length = jsonString.length()+10; String lenString = getLenString(length); String totalString = trxString+lenString+jsonString; logger.debug("totalString:"+totalString); Client client = new Client("88.6.13.66", 13000,totalString); client.start(); String result = client.result; logger.debug("result:"+result); result = result.substring(5,result.length()); moduleUtil.setParamValue(VALUE, result); logger.debug("VALUE:"+result); JSONObject resultJsonObject = JSONObject.parseObject(result); logger.debug("resultJsonObject:"+resultJsonObject); //新增参数 }else if("check".equals(type)) { paramMap.put("trxZone", trxZone); paramMap.put("programName", "e"); paramMap.put("id", id); paramMap.put("img1", imgBase64); paramMap.put("imgFace1", "50,60,100,120"); paramMap.put("threshold", 0.001); paramMap.put("hack1", 1); String trxString = "10034"; String jsonString = paramMap.toJSONString(); int length = jsonString.length()+10; String lenString = getLenString(length); String totalString = trxString+lenString+jsonString; logger.debug("totalString:"+totalString); Client client = new Client("88.6.13.66", 13000,totalString); client.start(); String result = client.result; logger.debug("result:"+result); result = result.substring(5,result.length()); moduleUtil.setParamValue(VALUE, result); logger.debug("VALUE:"+result); JSONObject resultJsonObject = JSONObject.parseObject(result); logger.debug("resultJsonObject:"+resultJsonObject); }else if("del".equals(type)){ paramMap.put("trxZone", trxZone); paramMap.put("programName", "e"); paramMap.put("id", id); String trxString = "10035"; String jsonString = paramMap.toJSONString(); int length = jsonString.length()+10; String lenString = getLenString(length); String totalString = trxString+lenString+jsonString; logger.debug("totalString:"+totalString); try { totalString = new String(totalString.getBytes(),"GBK"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } Client client = new Client("88.6.13.66", 13000,totalString); client.start(); String result = client.result; logger.debug("result:"+result); result = result.substring(5,result.length()); moduleUtil.setParamValue(VALUE, result); logger.debug("VALUE:"+result); JSONObject resultJsonObject = JSONObject.parseObject(result); logger.debug("resultJsonObject:"+resultJsonObject); }else { CommonUtil.setResponseMsg("FFFFF", "错误的操作类型", moduleUtil); return "fail"; } String param = paramMap.toJSONString(); try { param = "params="+URLEncoder.encode(param,"UTF-8"); } catch (UnsupportedEncodingException e) { logger.error("转换为请求数据失败"); return "fail"; } return "ok"; } /** * <p> 函数名:isRegisted </p> * <p> 函数功能:查询该编号用户人脸信息是否已注册 </p> * <p> 处理过程:(描述这个方法的处理逻辑)</p> * <p> 输入参数描述: </p> * <p> 输出参数描述: </p> * <p> 异常处理描述: </p> * <p> 创建信息:liuyuan/2019年6月4日 下午3:29:48/versoin</p> * <p> 修改信息:(修改人名、修改人名.../最后修改时间/修改版本号)</p> * <p> 多个版本修改,则每次新增一行修改信息</p> * @throws Exception */ private boolean isRegisted(String id,Connection conn,ZjLogger logger) throws Exception { String sql = "select t.id from USER_FACE_RECORD t where t.id_number=? or t.user_no=?"; List<SQLPara> sqlParas = new ArrayList<>(); sqlParas.add(new SQLPara("id_number", Types.VARCHAR, id)); sqlParas.add(new SQLPara("user_no", Types.VARCHAR, id)); CachedRowSet rlt = DbOperate.executeQueryByParamName(sql, sqlParas, conn, logger); return rlt.next(); } /** * * <p>Title: getSysParam</p> * <p>Description: 查询人脸识别相关参数 </p> * @param type * @param conn * @param logger * @return * @throws TradeException * @throws Exception */ private JSONObject getSysParam(String type,Connection conn, ZjLogger logger) throws TradeException,Exception { JSONObject sysParam = new JSONObject(); String qrySysParamSQL = " select t.param_value from SYS_PARAM t where t.param_name=? "; List<SQLPara> sqlParas = new ArrayList<>(); // 查询ip sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_ip")); CachedRowSet ipRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!ipRlt.next()) { throw new TradeException("请先配置人脸识别服务器地址(faceCheck_ip)"); } sysParam.put("ip",ipRlt.getString("param_value")); sqlParas.clear(); // 查询url sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_url")); CachedRowSet urlRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!urlRlt.next()) { throw new TradeException("请先配置人脸识别转发url(faceCheck_url)"); } sysParam.put("url",urlRlt.getString("param_value")); sqlParas.clear(); // 查询baseFlag sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_baseFlag")); CachedRowSet baseFlagRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!baseFlagRlt.next()) { throw new TradeException("请先配置人脸识基准照标示(faceCheck_baseFlag)"); } sysParam.put("baseFlag",baseFlagRlt.getInt("param_value")); sqlParas.clear(); // 查询threshold sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_threshold")); CachedRowSet thresholdRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!thresholdRlt.next()) { throw new TradeException("请先配置人脸识误识率阈值(faceCheck_threshold)"); } sysParam.put("threshold",thresholdRlt.getString("param_value")); sqlParas.clear(); //查询channel sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_channel")); CachedRowSet channelRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!channelRlt.next()) { throw new TradeException("请先配置人脸识别转发业务渠道编号(faceCheck_channel)"); } sysParam.put("channel",channelRlt.getString("param_value")); sqlParas.clear(); //交易编号写死,加操作类型大写进行区分 sysParam.put("trCode","SXFH-BF-SWXJ-ITMS-FACE-"+type.toUpperCase()); //查询appName sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_appName")); CachedRowSet appNameRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!appNameRlt.next()) { throw new TradeException("请先配置人脸识别应用名(faceCheck_appName)"); } sysParam.put("appName",appNameRlt.getString("param_value")); sqlParas.clear(); //查询appInfo sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_appInfo")); CachedRowSet appInfoRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!appInfoRlt.next()) { throw new TradeException("请先配置人脸识别客户端APP信息(faceCheck_appInfo)"); } sysParam.put("appInfo",appInfoRlt.getString("param_value")); sqlParas.clear(); //查询retentionTime sqlParas.add(new SQLPara("param_name", Types.VARCHAR, "faceCheck_retentionTime")); CachedRowSet retentionTimeRlt = DbOperate.executeQueryByParamName(qrySysParamSQL, sqlParas, conn, logger); if (!retentionTimeRlt.next()) { throw new TradeException("请先配置人脸识清理时间(faceCheck_retentionTime)"); } sysParam.put("retentionTime",retentionTimeRlt.getString("param_value")); sqlParas.clear(); logger.debug("sysParam:"+sysParam); return sysParam; } public String getLenString (int length) { NumberFormat formatter = NumberFormat.getNumberInstance(); formatter.setMinimumIntegerDigits(5); formatter.setGroupingUsed(false); String lenString = formatter.format(length); return lenString; } } ``` 这个地方为什么总是空的 ![图片说明](https://img-ask.csdn.net/upload/201912/12/1576144606_651895.png)
使用socket通信,android客户端,java写的服务器,传输数据时总出现异常
客户端: public void run() { // TODO Auto-generated method stub try { s = new Socket(ip, port); DataOutputStream os = new DataOutputStream(s.getOutputStream()); os.writeUTF("可以准备接收了吗?"); ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream()); out.writeObject(u); out.flush(); out.close(); System.out.println("用户名是:"+u.getID()); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ``` ``` 服务器: ``` try{ ServerSocket ss = new ServerSocket(9999); System.out.println("服务器正在监听!"); Socket s = ss.accept(); System.out.println("建立连接!"); DataInputStream is = new DataInputStream(s.getInputStream()); String str = is.readUTF(); System.out.println(str); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); User u = (User)ois.readObject(); ois.close(); System.out.println("用户ID :"+u.getID()); }catch(Exception e){ e.printStackTrace(); } ``` 异常: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.io.DataInputStream.readUnsignedShort(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at java.io.DataInputStream.readUTF(Unknown Source) at com.server.EasyServer.main(EasyServer.java:24) (在os.writeUTF一行)
TOMCAT运行一段时间后抛找不到主机异常,紧急。。。。。。。。。
TOMCAT运行一段时间后报:ava.net.UnknownHostException: 主机名,主机名:unknown error at java.net.InetAddress.getLocalHost(InetAddress.java:1484) at org.apache.jk.common.ChannelSocket.unLockSocket(ChannelSocket.java:490) at org.apache.jk.common.ChannelSocket.pause(ChannelSocket.java:288) at org.apache.jk.server.JkMain.pause(JkMain.java:739) at org.apache.jk.server.JkCoyoteHandler.pause(JkCoyoteHandler.java:153) at org.apache.catalina.connector.Connector.pause(Connector.java:1139) at org.apache.catalina.core.StandardService.stop(StandardService.java:578) at org.apache.catalina.core.StandardServer.stop(StandardServer.java:788) at org.apache.catalina.startup.Catalina.stop(Catalina.java:662) at org.apache.catalina.startup.Catalina.start(Catalina.java:629) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) 然后 紧接着报: SEVERE: The web application [/baas] is still processing a request that has yet to finish. This is very likely to create a memory leak. You can control the time allowed for requests to finish by using the unloadDelay attribute of the standard Context implementation. 一共报了500个内存泄漏。。。。。然后宕机 重启下就好了 然后一段时间后还是重复
java异常,具体描述如下,请问如何解决
程序代码如下: package mytest; import java.net.URL; import java.io.*; public class URLDemo { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub URL addr = new URL("file://E:/Detect.txt"); //本地文本文件 InputStream is = addr.openStream(); BufferedReader br = new BufferedReader( new InputStreamReader(is) ); while(true){ //从输入流不断读入数据,直到读完位置 String s = br.readLine(); if(null == s)break; System.out.println(s); } } } 运行错误: Exception in thread "main" java.net.UnknownHostException: E at java.net.AbstractPlainSocketImpl.connect(Unknown Source) at java.net.PlainSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.ftp.impl.FtpClient.doConnect(Unknown Source) at sun.net.ftp.impl.FtpClient.tryConnect(Unknown Source) at sun.net.ftp.impl.FtpClient.connect(Unknown Source) at sun.net.ftp.impl.FtpClient.connect(Unknown Source) at sun.net.www.protocol.ftp.FtpURLConnection.connect(Unknown Source) at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(Unknown Source) at java.net.URL.openStream(Unknown Source) at mytest.URLDemo.main(URLDemo.java:11) 请问如何解决?
java写了一个聊天室的程序 但是私聊第二个人就报空指针异常 不知道为什么 求解
下面是全部的代码 ``` package com.sram.chat; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class CrazyitMap<K,V> { Map<K,V> maps = Collections.synchronizedMap(new HashMap<K,V>()); //创建一个删除指定项 如果value值相同就删除 public synchronized void removeByValue(V value){ for(K key:maps.keySet()){ if(maps.get(key)==value){ maps.remove(key); break; } } } public synchronized Set<V> valueSet(){ Set<V> result = new HashSet<V>(); for(K key:maps.keySet()){ result.add(maps.get(key)); } return result; } //根据value查找key public synchronized K getKeyByValue(V value){ for(K key:maps.keySet()){ if(maps.get(key)==value||maps.get(key).equals(value)){ return key; } } return null; } //添加vlaue 但是不能重复 public synchronized V put(K key,V value){ for(V val:valueSet()){ if(val.equals(value)&&val.hashCode()==value.hashCode()){ throw new RuntimeException("Map集合中不能重复存储value"); } } return maps.put(key, value); } } ``` ``` package com.sram.chat; public interface Protocol { //定义协议字符长度 int PROTOCOL_LEN = 2; //下面是协议字符不同表示 String MEG_ROUND ="∞∞"; //发送群聊聊天信息 String USER_ROUND="ぁぁ"; //用户名 String LOGIN_SUCCESS="1"; //登录成功 String NAME_REP ="-1"; //重复用户名,登录失败 String PRIVATE_ROUND ="◎◎"; //私聊 String SPLIT_SIGN="π"; } ``` ``` package com.sram.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; import java.net.UnknownHostException; import javax.swing.JOptionPane; public class Client { private static final int SERVER_PORT = 6868; private Socket socket; private PrintStream ps; private BufferedReader brServer;// private BufferedReader keyIn;// public void init(){ try{ socket = new Socket("127.0.0.1",SERVER_PORT); keyIn = new BufferedReader(new InputStreamReader(System.in)); ps = new PrintStream(socket.getOutputStream()); brServer = new BufferedReader(new InputStreamReader(socket.getInputStream())); String tip = ""; while(true){ String userName = JOptionPane.showInputDialog(tip+"输入用户名"); ps.println(Protocol.USER_ROUND+userName+Protocol.USER_ROUND); String result = brServer.readLine(); if(result.equals(Protocol.NAME_REP)){ tip = "用户名重复,请重新"; continue; }else if(result.equals(Protocol.LOGIN_SUCCESS)){ break; } } }catch(UnknownHostException e){ System.out.println("链接不到远程服务器,请确定服务器已经启动"); closeAll(); System.exit(1); }catch(IOException e1){ System.out.println("网络异常!请重新登录"); closeAll(); System.exit(1); } new ClientThread(brServer).start(); } public void readAndSend(){ try { String line = null; while((line = keyIn.readLine())!=null){ if(line.indexOf(":")>0&&line.startsWith("@@")){ line = line.substring(2);// ps.println(Protocol.PRIVATE_ROUND +line.split(":")[0] +Protocol.SPLIT_SIGN +line.split(":")[1] +Protocol.PRIVATE_ROUND); }else{ ps.println(Protocol.MEG_ROUND+line+Protocol.MEG_ROUND); } } } catch (IOException e) {e.printStackTrace();} } public static void main(String[] args) { Client client = new Client(); client.init(); client.readAndSend(); } public void closeAll(){ try{ if(keyIn!=null){ //判断流是否创建 keyIn.close(); } if(brServer!=null){ brServer.close(); } if(ps!=null){ ps.close(); } if(socket!=null){ socket.close(); } } catch (IOException e){ e.printStackTrace(); } } } ``` ``` package com.sram.chat; import java.io.BufferedReader; import java.io.IOException; public class ClientThread extends Thread{ BufferedReader br = null;//处理 public ClientThread(BufferedReader br){ this.br= br; } @Override public void run() { String line = null; try { while((line = br.readLine())!=null){ System.out.println(line); } } catch (IOException e) {e.printStackTrace();} finally{ try{ if(br!=null){ br.close(); } }catch(IOException e){e.printStackTrace();} } } } ``` ``` package com.sram.chat; import java.io.IOException; import java.io.PrintStream; import java.net.ServerSocket; import java.net.Socket; public class Server { private static final int SERVER_PORT = 6868; public static CrazyitMap<String,PrintStream> clients = new CrazyitMap<>(); public void init(){ try{ ServerSocket ss = new ServerSocket(SERVER_PORT); while(true){ Socket s = ss.accept(); //启动子线程,读取 new ServerThread(s).start();; } }catch(IOException ex){ System.out.println("服务器启动失败,是否"+SERVER_PORT+"已被占用?"); } } public static void main(String args[]){ Server server = new Server(); server.init(); } } ``` ``` package com.sram.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.net.Socket; public class ServerThread extends Thread{ private Socket socket; BufferedReader br = null; PrintStream ps = null; ServerThread(Socket socket){ this.socket = socket; } @Override public void run() { try{ br = new BufferedReader(new InputStreamReader(socket.getInputStream())); ps = new PrintStream(socket.getOutputStream()); String line = null; while((line = br.readLine())!=null){ //ぁぁstevejobsぁぁ //如果读到的line字符是以 Protocol.USER_ROUND开始,并且以Protocol.USER_ROUND结束,则可以确定 //读到的是用户登录的用户名 //System.out.println(line); //System.out.println(getRealMsg(line)); if(line.startsWith(Protocol.USER_ROUND)&&line.endsWith(Protocol.USER_ROUND)){ String userName = getRealMsg(line); if(Server.clients.maps.containsKey(userName)){ System.out.println("服务器提示:用户名重复");//服务器端到客户端 ps.println(Protocol.NAME_REP); }else{ System.out.println("服务器提示:成功"); ps.println(Protocol.LOGIN_SUCCESS); Server.clients.put(userName,ps); } }else if(line.startsWith(Protocol.PRIVATE_ROUND)&&line.endsWith(Protocol.PRIVATE_ROUND)){ String message = getRealMsg(line); String toUser = message.split(Protocol.SPLIT_SIGN)[0]; String msg = message.split(Protocol.SPLIT_SIGN)[1]; Server.clients.maps.get(toUser).println(Server.clients.getKeyByValue(ps)+"悄悄对你说:"+msg); }else if(line.startsWith(Protocol.MEG_ROUND)&&line.startsWith(Protocol.MEG_ROUND)){ String message = getRealMsg(line); for(PrintStream out:Server.clients.valueSet()){ out.println(Server.clients.getKeyByValue(ps)+"说:"+message); } } } }catch(IOException e){ Server.clients.removeByValue(ps); System.out.println("集合Map"+Server.clients.maps.size()); try { if(br!=null){ br.close(); } if(ps!=null){ ps.close(); } if(socket!=null){ socket.close(); } } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } } private String getRealMsg(String line){ return line.substring(Protocol.PROTOCOL_LEN,line.length()-Protocol.PROTOCOL_LEN); } } ```
调用Java接口InetAddress.getAllByName得到两种不同的结果
- 1. 我在java APP上创建一个下载线程,文件下载失败后重试,重试前,先调用接口InetAddress.getAllByName()。 - 2. 把程序运行起来,然后断开网络,2分钟后,打开网络,发现下载线程中调用接口InetAddress.getAllByName()总是捕获到异常UnknownHostException。 - 3. 我在我的程序里面添加一个循环不断地去调用接口InetAddress.getAllByName(). - 4. 然后重复步骤2,发现最后两个线程都能正确获取到ip和host name. 运行环境: Centos7 OpenJDK1.8
mongo连接数和maxCons设置为20000,还是频繁报连接数不够异常
异常和连接池的配置如下: ``` com.mongodb.DBPortPool$SemaphoresOut: Out of semaphores to get db connection at com.mongodb.DBPortPool.get(DBPortPool.java:206) at com.mongodb.DBTCPConnector$MyPort.get(DBTCPConnector.java:437) at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:277) at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:256) at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:289) at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:274) at com.mongodb.DBCollection.findOne(DBCollection.java:710) at com.mongodb.DBCollection.findOne(DBCollection.java:652) at com.hzwaso.miniapp.business.action.WeChatGraphicEditingPushAction.getTitle(WeChatGraphicEditingPushAction.java:1291) at com.hzwaso.miniapp.business.action.WeChatGraphicEditingPushAction.queryDetail(WeChatGraphicEditingPushAction.java:135) at sun.reflect.GeneratedMethodAccessor132.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:892) at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1294) at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68) at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:117) at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:108) at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1370) at ognl.ASTMethod.getValueBody(ASTMethod.java:91) at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212) at ognl.SimpleNode.getValue(SimpleNode.java:258) at ognl.Ognl.getValue(Ognl.java:467) at ognl.Ognl.getValue(Ognl.java:431) at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:352) at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:404) at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:350) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:430) at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:290) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:251) at org.apache.struts2.interceptor.DeprecationInterceptor.intercept(DeprecationInterceptor.java:41) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:168) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265) at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:76) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:229) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:229) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:125) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:253) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171) at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:140) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189) at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:245) at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:575) at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:81) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99) at com.hzwaso.miniapp.business.filter.EditorStrutsFilter.doFilter(EditorStrutsFilter.java:21) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.hzwaso.miniapp.common.filter.EncodedFilter.doFilter(EncodedFilter.java:24) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at com.hzwaso.miniapp.business.filter.WeChatFilter.doFilter(WeChatFilter.java:844) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) public class MongoUtil { private static Mongo mongo = null; private static DB db = null; private final static int POOLSIZE = 5000;// 连接数量 private final static int BLOCKSIZE = 1000; // 等待队列长度 private static Log log = LogFactory.getLog(MongoUtil.class); /** * 根据名称获取DB,相当于是连接 * * @param dbName * @return */ public static DB getMongoDB() { if (mongo == null) { init(); db = mongo.getDB(ConfigUtils.systemConf("mongo.db")); db.authenticate(ConfigUtils.systemConf("mongo.user"), ConfigUtils.systemConf("mongo.pwd").toCharArray()); } return db; } private static void init() { String host = ConfigUtils.systemConf("mongo.ip"); int port = new Integer("27017"); try { mongo = new Mongo(host, port); MongoOptions opt = mongo.getMongoOptions(); opt.connectionsPerHost = POOLSIZE; opt.threadsAllowedToBlockForConnectionMultiplier = BLOCKSIZE; } catch (UnknownHostException e) { log.error(e); } catch (MongoException e) { mongo.close(); mongo = null; log.error(e); } } } ```
Java广播相关问题,我到底应该使用什么广播地址才可以发送广播消息。谢谢
网上查询关于JAVA广播的问题,关于广播地址有一些问题。有的人说广播地址是D类地址,有人说广播地址是当前ip地址最后一位换成255,有人说广播地址是全部为255的地址,现在测试结果如果全部是255在本机发送广播本机可以收到,其他的D类地址无法收到TTL已经设置为128,最后一个换成255的会被MultiScoketCast抛出不是多播地址的异常。请问他们之间有什么区别和联系各个的用法又是如何。 现在问题:我当前ip地址10.13.242.116.使用相关类MulticastSocket。测试结果: 当我使用D类地址进行广播,可以发送但是无法接收。设置可以发回本机,本机无法收到广播包。其他机器也无法收到广播包。其他机器均为10.13.*.* 当我使用本机地址最后一个字节全部变为255的时候例如:10.13.242.255此时抛出此地址不是广播地址的异常,无法发送。 当我使用全1的地址发送广播的时候例如:255.255.255.255此时本机可以收到广播包但是其他机器无法收到广播包.不知道为什么.谢谢各位的帮助.下面贴出我的最后一种实验的代码. 发送者 `import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.sql.Date; public class MulticastSender extends Thread { private int port = 9898; private InetAddress ipaAddress = null; MulticastSocket msocket; MulticastSender(){ try { ipaAddress = InetAddress.getByName("255.255.255.255"); msocket = new MulticastSocket(port); msocket.setBroadcast(true); msocket.setTimeToLive(1); msocket.joinGroup(ipaAddress); } catch (Exception e) { // TODO: handle exception } } @Override public void run(){ while(true) try { String string="Hello"; byte [] buf = string.getBytes(); DatagramPacket datagramPacket = new DatagramPacket(buf, 0, buf.length, ipaAddress, port); System.out.println("发送数据"); msocket.send(datagramPacket); System.out.println("发送成功"); Thread.sleep(2000); } catch (Exception e) { // TODO: handle exception } } public static void main(String[] args) throws Exception { MulticastSender msMulticastSender = new MulticastSender(); msMulticastSender.start(); } } ` 接受者 import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; public class MulticastReciever extends Thread{ private int port = 9898; private InetAddress ipgroupAddress =null; private MulticastSocket msMulticastSocket = null; DatagramPacket datagramPacket = null; MulticastReciever(){ try { msMulticastSocket = new MulticastSocket(port); //ipgroupAddress = InetAddress.getByName("10.13.255.255"); //msMulticastSocket.joinGroup(ipgroupAddress); byte[] data = new byte[4096]; datagramPacket = new DatagramPacket(data, data.length); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run(){ try { while (true) { msMulticastSocket.receive(datagramPacket); System.out.println("接收到数据"+new String(datagramPacket.getData())); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) throws Exception { MulticastReciever multicastReciever = new MulticastReciever(); multicastReciever.start(); } } 这种情况下我本机可以收到广播内容,但是其他机器10.13.*.*无法收到广播包。谢谢
mq问题,谁能给注释一下。看不懂了
package com.dcsoft.sdfq.activeMq.sender; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.log4j.Logger; import com.dcsoft.sdfq.activeMq.db.DBQuery; import com.dcsoft.sdfq.activeMq.util.LoadProperties; import com.dcsoft.sdfq.activeMq.util.ToolSupport; import dba.DBMap; public class SendMessageThread extends Thread { public static Logger log = Logger.getLogger(SendMessageThread.class); private SmsMQSender sms = null; private String clientIpTemp = ""; public SendMessageThread(String id) { super(id); } public void run() { // 与消息中间件进行通讯的对象 sms = new SmsMQSender(); // 获取本地客户端ip String ips = null; String[] strs = getAllIP(); if (strs != null && strs.length > 0) { String ipPrefix = LoadProperties.getInstance().readINI("clientID"); ips = ipPrefix; } if (ips == null) return; clientIpTemp = "tcp://" + ips + ":6161"; while (true) { // CheckExistsMessage.check(); checkAndSend(); SendMessageThread smt = (SendMessageThread) Thread.currentThread(); smt.shortWaiting(); } } private void checkAndSend() { String returnID = ""; ResultSet rst, sscs, xzqh = null; try { DBQuery db = new DBQuery(); // 查询任务表 String sql = "SELECT TOP 1 * FROM tbl_sender WHERE senderType = 0"; ResultSet rs = db.executeQuery(sql); if (rs.next()) { String id = rs.getString("id"); String tblName = rs.getString("tblName"); String idName = rs.getString("idName"); String idValue = rs.getString("idValue"); String dealType = rs.getString("dealType"); String clxxid = rs.getString("clxxid"); String dataType = rs.getString("dataType"); String chp = rs.getString("cph"); db.closeAll(); // 查询需要同步的数据 if (dealType.equals("delete")) { db = new DBQuery(); String sqlDel = "update " + tblName + " set datatype='2' where " + idName + " = '" + idValue + "'"; db.executeUpdate(sqlDel); db.closeAll(); sql = "select '" + idValue + "' as " + idName; } else sql = "select * from " + tblName + " where " + idName + " = '" + idValue + "'"; rs.close(); rs = null; db = new DBQuery(); rs = db.executeQuery(sql); DBMap dbmap = new DBMap(rs, tblName, id, clientIpTemp, idName, dealType, clxxid, idValue, dataType, chp, new ToolSupport() .getCityByDwbm(LoadProperties.getInstance().readINI("dwbh")), new ToolSupport().getXzqhByDwbm(LoadProperties.getInstance().readINI( "dwbh"))); db.closeAll(); if (dbmap.isEmpty()) { sql = "delete from tbl_sender where (tblName = '" + tblName + "' and idValue = '" + idValue + "') "; db = new DBQuery(); db.executeUpdate(sql); db.closeAll(); return; } // 发送消息 returnID = sms.sendMessage(dbmap); if (!returnID.equalsIgnoreCase("")) { sql = "UPDATE tbl_sender SET senderType = 1, sendtime = getdate() WHERE id = '" + returnID + "'"; db = new DBQuery(); db.executeUpdate(sql); db.closeAll(); } } else { db.closeAll(); SendMessageThread smt = (SendMessageThread) Thread.currentThread(); smt.longWaiting(); } } catch (SQLException e) { log.info("SendMessageThread 异常1:" + e); SendMessageThread smt = (SendMessageThread) Thread.currentThread(); smt.longWaiting(); } catch (Exception e) { log.info("SendMessageThread 异常2:" + e); SendMessageThread smt = (SendMessageThread) Thread.currentThread(); smt.longWaiting(); } return; } void shortWaiting() { try { sleep(Integer.parseInt(LoadProperties.getInstance().readINI("clientSenderThreadTime"))); // 发送消息 } catch (Exception e) { log.info("SendMessageThread.java 休眠异常" + e); } } void MiddleWaiting() { try { sleep(Integer.parseInt(LoadProperties.getInstance().readINI("clientSenderThreadMiddleTime")));// 中断情况 } catch (Exception e) { log.info("SendMessageThread.java 休眠异常" + e); } } void longWaiting() { try { sleep(Integer.parseInt(LoadProperties.getInstance().readINI("clientSenderThreadLongTime"))); // 异常情况 } catch (Exception e) { log.warn("SendMessageThread.java 休眠异常" + e); } } public static String[] getAllIP() { try { InetAddress localHost = InetAddress.getLocalHost(); String hostName = localHost.getHostName(); InetAddress[] inetAdds = InetAddress.getAllByName(hostName); String[] ips = new String[inetAdds.length]; for (int i = 0; i < inetAdds.length; i++) ips[i] = inetAdds[i].getHostAddress(); return ips; } catch (UnknownHostException e) { e.printStackTrace(); } return null; } }
在中国程序员是青春饭吗?
今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...
《MySQL 性能优化》之理解 MySQL 体系结构
本文介绍 MySQL 的体系结构,包括物理结构、逻辑结构以及插件式存储引擎。
程序员请照顾好自己,周末病魔差点一套带走我。
程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。
复习一周,京东+百度一面,不小心都拿了Offer
京东和百度一面都问了啥,面试官百般刁难,可惜我全会。
Java 14 都快来了,为什么还有这么多人固守Java 8?
从Java 9开始,Java版本的发布就让人眼花缭乱了。每隔6个月,都会冒出一个新版本出来,Java 10 , Java 11, Java 12, Java 13, 到2020年3月份,...
达摩院十大科技趋势发布:2020 非同小可!
【CSDN编者按】1月2日,阿里巴巴发布《达摩院2020十大科技趋势》,十大科技趋势分别是:人工智能从感知智能向认知智能演进;计算存储一体化突破AI算力瓶颈;工业互联网的超融合;机器间大规模协作成为可能;模块化降低芯片设计门槛;规模化生产级区块链应用将走入大众;量子计算进入攻坚期;新材料推动半导体器件革新;保护数据隐私的AI技术将加速落地;云成为IT技术创新的中心 。 新的画卷,正在徐徐展开。...
轻松搭建基于 SpringBoot + Vue 的 Web 商城应用
首先介绍下在本文出现的几个比较重要的概念: 函数计算(Function Compute): 函数计算是一个事件驱动的服务,通过函数计算,用户无需管理服务器等运行情况,只需编写代码并上传。函数计算准备计算资源,并以弹性伸缩的方式运行用户代码,而用户只需根据实际代码运行所消耗的资源进行付费。Fun: Fun 是一个用于支持 Serverless 应用部署的工具,能帮助您便捷地管理函数计算、API ...
讲真,这两个IDE插件,可以让你写出质量杠杠的代码
周末躺在床上看《拯救大兵瑞恩》 周末在闲逛的时候,发现了两个优秀的 IDE 插件,据说可以提高代码的质量,我就安装了一下,试了试以后发现,确实很不错,就推荐给大家。 01、Alibaba Java 代码规范插件 《阿里巴巴 Java 开发手册》,相信大家都不会感到陌生,其 IDEA 插件的下载次数据说达到了 80 万次,我今天又贡献了一次。嘿嘿。 该项目的插件地址: https://github....
Python+OpenCV实时图像处理
目录 1、导入库文件 2、设计GUI 3、调用摄像头 4、实时图像处理 4.1、阈值二值化 4.2、边缘检测 4.3、轮廓检测 4.4、高斯滤波 4.5、色彩转换 4.6、调节对比度 5、退出系统 初学OpenCV图像处理的小伙伴肯定对什么高斯函数、滤波处理、阈值二值化等特性非常头疼,这里给各位分享一个小项目,可通过摄像头实时动态查看各类图像处理的特点,也可对各位调参、测试...
2020年一线城市程序员工资大调查
人才需求 一线城市共发布岗位38115个,招聘120827人。 其中 beijing 22805 guangzhou 25081 shanghai 39614 shenzhen 33327 工资分布 2020年中国一线城市程序员的平均工资为16285元,工资中位数为14583元,其中95%的人的工资位于5000到20000元之间。 和往年数据比较: yea...
为什么猝死的都是程序员,基本上不见产品经理猝死呢?
相信大家时不时听到程序员猝死的消息,但是基本上听不到产品经理猝死的消息,这是为什么呢? 我们先百度搜一下:程序员猝死,出现将近700多万条搜索结果: 搜索一下:产品经理猝死,只有400万条的搜索结果,从搜索结果数量上来看,程序员猝死的搜索结果就比产品经理猝死的搜索结果高了一倍,而且从下图可以看到,首页里面的五条搜索结果,其实只有两条才是符合条件。 所以程序员猝死的概率真的比产品经理大,并不是错...
害怕面试被问HashMap?这一篇就搞定了!
声明:本文以jdk1.8为主! 搞定HashMap 作为一个Java从业者,面试的时候肯定会被问到过HashMap,因为对于HashMap来说,可以说是Java集合中的精髓了,如果你觉得自己对它掌握的还不够好,我想今天这篇文章会非常适合你,至少,看了今天这篇文章,以后不怕面试被问HashMap了 其实在我学习HashMap的过程中,我个人觉得HashMap还是挺复杂的,如果真的想把它搞得明明白...
毕业5年,我问遍了身边的大佬,总结了他们的学习方法
我问了身边10个大佬,总结了他们的学习方法,原来成功都是有迹可循的。
python爬取百部电影数据,我分析出了一个残酷的真相
2019年就这么匆匆过去了,就在前几天国家电影局发布了2019年中国电影市场数据,数据显示去年总票房为642.66亿元,同比增长5.4%;国产电影总票房411.75亿元,同比增长8.65%,市场占比 64.07%;城市院线观影人次17.27亿,同比增长0.64%。 看上去似乎是一片大好对不对?不过作为一名严谨求实的数据分析师,我从官方数据中看出了一点端倪:国产票房增幅都已经高达8.65%了,为什...
推荐10个堪称神器的学习网站
每天都会收到很多读者的私信,问我:“二哥,有什么推荐的学习网站吗?最近很浮躁,手头的一些网站都看烦了,想看看二哥这里有什么新鲜货。” 今天一早做了个恶梦,梦到被老板辞退了。虽然说在我们公司,只有我辞退老板的份,没有老板辞退我这一说,但是还是被吓得 4 点多都起来了。(主要是因为我掌握着公司所有的核心源码,哈哈哈) 既然 4 点多起来,就得好好利用起来。于是我就挑选了 10 个堪称神器的学习网站,推...
这些软件太强了,Windows必装!尤其程序员!
Windows可谓是大多数人的生产力工具,集娱乐办公于一体,虽然在程序员这个群体中都说苹果是信仰,但是大部分不都是从Windows过来的,而且现在依然有很多的程序员用Windows。 所以,今天我就把我私藏的Windows必装的软件分享给大家,如果有一个你没有用过甚至没有听过,那你就赚了????,这可都是提升你幸福感的高效率生产力工具哦! 走起!???? NO、1 ScreenToGif 屏幕,摄像头和白板...
阿里面试,面试官没想到一个ArrayList,我都能跟他扯半小时
我是真的没想到,面试官会这样问我ArrayList。
曾经优秀的人,怎么就突然不优秀了。
职场上有很多辛酸事,很多合伙人出局的故事,很多技术骨干被裁员的故事。说来模板都类似,曾经是名校毕业,曾经是优秀员工,曾经被领导表扬,曾经业绩突出,然而突然有一天,因为种种原因,被裁员了,...
大学四年因为知道了这32个网站,我成了别人眼中的大神!
依稀记得,毕业那天,我们导员发给我毕业证的时候对我说“你可是咱们系的风云人物啊”,哎呀,别提当时多开心啦????,嗯,我们导员是所有导员中最帅的一个,真的???? 不过,导员说的是实话,很多人都叫我大神的,为啥,因为我知道这32个网站啊,你说强不强????,这次是绝对的干货,看好啦,走起来! PS:每个网站都是学计算机混互联网必须知道的,真的牛杯,我就不过多介绍了,大家自行探索,觉得没用的,尽管留言吐槽吧???? 社...
良心推荐,我珍藏的一些Chrome插件
上次搬家的时候,发了一个朋友圈,附带的照片中不小心暴露了自己的 Chrome 浏览器插件之多,于是就有小伙伴评论说分享一下我觉得还不错的浏览器插件。 我下面就把我日常工作和学习中经常用到的一些 Chrome 浏览器插件分享给大家,随便一个都能提高你的“生活品质”和工作效率。 Markdown Here Markdown Here 可以让你更愉快的写邮件,由于支持 Markdown 直接转电子邮...
看完这篇HTTP,跟面试官扯皮就没问题了
我是一名程序员,我的主要编程语言是 Java,我更是一名 Web 开发人员,所以我必须要了解 HTTP,所以本篇文章就来带你从 HTTP 入门到进阶,看完让你有一种恍然大悟、醍醐灌顶的感觉。 最初在有网络之前,我们的电脑都是单机的,单机系统是孤立的,我还记得 05 年前那会儿家里有个电脑,想打电脑游戏还得两个人在一个电脑上玩儿,及其不方便。我就想为什么家里人不让上网,我的同学 xxx 家里有网,每...
2020 年,大火的 Python 和 JavaScript 是否会被取而代之?
Python 和 JavaScript 是目前最火的两大编程语言,但是2020 年,什么编程语言将会取而代之呢? 作者 |Richard Kenneth Eng 译者 |明明如月,责编 | 郭芮 出品 | CSDN(ID:CSDNnews) 以下为译文: Python 和 JavaScript 是目前最火的两大编程语言。然而,他们不可能永远屹立不倒。最终,必将像其他编程语言一...
史上最全的IDEA快捷键总结
现在Idea成了主流开发工具,这篇博客对其使用的快捷键做了总结,希望对大家的开发工作有所帮助。
阿里程序员写了一个新手都写不出的低级bug,被骂惨了。
这种新手都不会范的错,居然被一个工作好几年的小伙子写出来,差点被当场开除了。
谁是华为扫地僧?
是的,华为也有扫地僧!2020年2月11-12日,“养在深闺人不知”的华为2012实验室扫地僧们,将在华为开发者大会2020(Cloud)上,和大家见面。到时,你可以和扫地僧们,吃一个洋...
Idea 中最常用的10款插件(提高开发效率),一定要学会使用!
学习使用一些插件,可以提高开发效率。对于我们开发人员很有帮助。这篇博客介绍了开发中使用的插件。
AI 没让人类失业,搞 AI 的人先失业了
最近和几个 AI 领域的大佬闲聊 根据他们讲的消息和段子 改编出下面这个故事 如有雷同 都是巧合 1. 老王创业失败,被限制高消费 “这里写我跑路的消息实在太夸张了。” 王葱葱哼笑一下,把消息分享给群里。 阿杰也看了消息,笑了笑。在座几位也都笑了。 王葱葱是个有名的人物,21岁那年以全额奖学金进入 KMU 攻读人工智能博士,累计发表论文 40 余篇,个人技术博客更是成为深度学习领域内风向标。 ...
2020年,冯唐49岁:我给20、30岁IT职场年轻人的建议
点击“技术领导力”关注∆每天早上8:30推送 作者|Mr.K 编辑| Emma 来源|技术领导力(ID:jishulingdaoli) 前天的推文《冯唐:职场人35岁以后,方法论比经验重要》,收到了不少读者的反馈,觉得挺受启发。其实,冯唐写了不少关于职场方面的文章,都挺不错的。可惜大家只记住了“春风十里不如你”、“如何避免成为油腻腻的中年人”等不那么正经的文章。 本文整理了冯...
作为一名大学生,如何在B站上快乐的学习?
B站是个宝,谁用谁知道???? 作为一名大学生,你必须掌握的一项能力就是自学能力,很多看起来很牛X的人,你可以了解下,人家私底下一定是花大量的时间自学的,你可能会说,我也想学习啊,可是嘞,该学习啥嘞,不怕告诉你,互联网时代,最不缺的就是学习资源,最宝贵的是啥? 你可能会说是时间,不,不是时间,而是你的注意力,懂了吧! 那么,你说学习资源多,我咋不知道,那今天我就告诉你一个你必须知道的学习的地方,人称...
那些年,我们信了课本里的那些鬼话
教材永远都是有错误的,从小学到大学,我们不断的学习了很多错误知识。 斑羚飞渡 在我们学习的很多小学课文里,有很多是错误文章,或者说是假课文。像《斑羚飞渡》: 随着镰刀头羊的那声吼叫,整个斑羚群迅速分成两拨,老年斑羚为一拨,年轻斑羚为一拨。 就在这时,我看见,从那拨老斑羚里走出一只公斑羚来。公斑羚朝那拨年轻斑羚示意性地咩了一声,一只半大的斑羚应声走了出来。一老一少走到伤心崖,后退了几步,突...
立即提问