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
企业号开发时,偶尔出现这种异常,过一段时间又好使了,不知道是代码问题?网络问题?
重金求解,为什么我接收不到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)
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块行不行。 拜托了,帮帮我吧。
百度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**
使用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一行)
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) 请问如何解决?
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 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; } }
相见恨晚的超实用网站
相见恨晚的超实用网站 持续更新中。。。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
python 简易微信实现(注册登录+数据库存储+聊天+GUI+文件传输)
socket+tkinter详解+简易微信实现 历经多天的努力,查阅了许多大佬的博客后终于实现了一个简易的微信O(∩_∩)O~~ 简易数据库的实现 使用pands+CSV实现数据库框架搭建 import socket import threading from pandas import * import pymysql import csv # 创建DataFrame对象 # 存储用户数据的表(...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
JavaScript 为什么能活到现在?
作者 | 司徒正美 责编 |郭芮 出品 | CSDN(ID:CSDNnews) JavaScript能发展到现在的程度已经经历不少的坎坷,早产带来的某些缺陷是永久性的,因此浏览器才有禁用JavaScript的选项。甚至在jQuery时代有人问出这样的问题,jQuery与JavaScript哪个快?在Babel.js出来之前,发明一门全新的语言代码代替JavaScript...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
Nginx 原理和架构
Nginx 是一个免费的,开源的,高性能的 HTTP 服务器和反向代理,以及 IMAP / POP3 代理服务器。Nginx 以其高性能,稳定性,丰富的功能,简单的配置和低资源消耗而闻名。 Nginx 的整体架构 Nginx 里有一个 master 进程和多个 worker 进程。master 进程并不处理网络请求,主要负责调度工作进程:加载配置、启动工作进程及非停升级。worker 进程负责处...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
吐血推荐珍藏的Visual Studio Code插件
作为一名Java工程师,由于工作需要,最近一个月一直在写NodeJS,这种经历可以说是一部辛酸史了。好在有神器Visual Studio Code陪伴,让我的这段经历没有更加困难。眼看这段经历要告一段落了,今天就来给大家分享一下我常用的一些VSC的插件。 VSC的插件安装方法很简单,只需要点击左侧最下方的插件栏选项,然后就可以搜索你想要的插件了。 下面我们进入正题 Material Theme ...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
开源并不是你认为的那些事
点击上方蓝字 关注我们开源之道导读所以 ————想要理清开源是什么?先要厘清开源不是什么,名正言顺是句中国的古代成语,概念本身的理解非常之重要。大部分生物多样性的起源,...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
Python 植物大战僵尸代码实现(2):植物卡片选择和种植
这篇文章要介绍的是: - 上方植物卡片栏的实现。 - 点击植物卡片,鼠标切换为植物图片。 - 鼠标移动时,判断当前在哪个方格中,并显示半透明的植物作为提示。
相关热词 c#委托 逆变与协变 c#新建一个项目 c#获取dll文件路径 c#子窗体调用主窗体事件 c# 拷贝目录 c# 调用cef 网页填表c#源代码 c#部署端口监听项目、 c#接口中的属性使用方法 c# 昨天
立即提问