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.(Socket.java:434)
at java.net.Socket.(Socket.java:211)
at app21.SocketTest1.main(SocketTest1.java:16)

3个回答

改成这个
Socket socket = new Socket(host, 80);

哥们,建议你在cmd中ping一下,看你的本机是否能够连接到百度 。。 估计你没有联网 。

不要https://

Socket socket = new Socket("www.baidu.com", 80);

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
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 UnknownHostException异常
如下错误 ``` java.net.UnknownHostException: apis.baidu.com ``` 求解答呀!!
微信企业号调用接口时java.net.UnknownHostException: qyapi.weixin.qq.com
企业号开发时,偶尔出现这种异常,过一段时间又好使了,不知道是代码问题?网络问题?
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) 请问如何解决?
百度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)
UnknownHostException异常
测试环境,用http发送get请求文件服务器下载文件,显示找不到UnknownHostException,但是用a标签href可以直接访问下载![图片说明](https://img-ask.csdn.net/upload/201908/23/1566517323_101388.jpg) ![图片说明](https://img-ask.csdn.net/upload/201908/23/1566517336_850208.jpg)
使用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网络编程的一些问题
入口类: [code="java"]package socketone; public class Main { /** * @param args */ public static void main(String[] args) { //开启线程数 int threadCount=5; //最大端口号 int maxPort=1000; //最小端口号 int minPort=1; //端口递增量 int portIncremenr=((maxPort-minPort+1)/threadCount)+((maxPort-minPort+1)%threadCount==0?0:1); SocketOne[] instances=new SocketOne[threadCount]; //利用多线程将这个端口范围分成不同的段进行扫描 for(int i=0;i<threadCount;i++){ instances[i]=new SocketOne(minPort+portIncremenr*i,minPort+portIncremenr*i+portIncremenr-1); Thread thread =new Thread(instances[i]); thread.start(); } } } [/code] 端口扫描类: [code="java"]package socketone; import java.io.IOException; import java.net.Socket; import java.net.UnknownHostException; public class SocketOne implements Runnable{ //最小端口号 private int minPort; //最大端口号 private int maxPort; public SocketOne(int minPort, int maxPort) { super(); this.minPort = minPort; this.maxPort = maxPort; } @Override public void run() { for(int i=minPort;i<=maxPort;i++){ try { Socket socket=new Socket("127.0.0.1", i); if(socket.isConnected()){ System.out.println("端口号:"+i+" 打开!"); } socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } [/code] 就是很简单的一个本机端口扫描,利用多线程分配扫描端口范围,但是却一直提示以下异常: [code="java"]java.net.ConnectException: Connection refused: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(Unknown Source) at java.net.PlainSocketImpl.connectToAddress(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 java.net.Socket.<init>(Unknown Source) at java.net.Socket.<init>(Unknown Source) at socketone.SocketOne.run(SocketOne.java:23) at java.lang.Thread.run(Unknown Source) [/code] 连接被拒绝,很是疑惑,连接本机都拒绝,但是在cmd下,我用telnet是可以连接的,系统是win7,大家知道怎么回事吗? 希望能帮忙解答下,小弟感激不尽!!!
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的异常,是什么原因?
struts2工程不联网启动报错!
原来使用的struts1.3,后来升级到struts2+jdk6。tomcat6联网情况下使用正常,不联网时,启动就报异常: [code="java"]Caused by: java.net.UnknownHostException: struts.apache.org at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177) at java.net.Socket.connect(Socket.java:519) at java.net.Socket.connect(Socket.java:469) at sun.net.NetworkClient.doConnect(NetworkClient.java:157) at sun.net.www.http.HttpClient.openServer(HttpClient.java:388) at sun.net.www.http.HttpClient.openServer(HttpClient.java:500) at sun.net.www.http.HttpClient.<init>(HttpClient.java:233) at sun.net.www.http.HttpClient.New(HttpClient.java:306) at sun.net.www.http.HttpClient.New(HttpClient.java:318) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:792) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:733) at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:658) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:981) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(XMLEntityManager.java:677) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startEntity(XMLEntityManager.java:1316) at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.startDTDEntity(XMLEntityManager.java:1283) at com.sun.org.apache.xerces.internal.impl.XMLDTDScannerImpl.setInputSource(XMLDTDScannerImpl.java:283) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.dispatch(XMLDocumentScannerImpl.java:1168) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$DTDDriver.next(XMLDocumentScannerImpl.java:1068) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:988) at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:645) at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:508) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807) at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737) at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107) at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:225) at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:283) at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:78) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:361) ... 27 more[/code] 上网搜索了,看到有人说要使用本地加载DTD文件,于是修改struts.xml文件,为 [code="java"]<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "struts-2.0.dtd">[/code] struts-2.0.dtd文件放在和struts.xml相同的路径,启动却报了这样一个异常: [code="java"]Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/struts-2.0.dtd][/code] 重建工程也是一样,请教是什么问题,多谢了!
javamail发送邮件失败问题?
这是报的异常:信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> z8kflt9u1dxx2q1feu2jv|1127b52, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> z8kflt9u1dxx2q1feu2jv|1127b52, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:///estoresystem, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ] javax.mail.MessagingException: Unknown SMTP host: smtp.qq.com; nested exception is: java.net.UnknownHostException: smtp.qq.com at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1932) at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638) at javax.mail.Service.connect(Service.java:317) at javax.mail.Service.connect(Service.java:176) at javax.mail.Service.connect(Service.java:125) at javax.mail.Transport.send0(Transport.java:194) at javax.mail.Transport.send(Transport.java:124) at cn.itcast.estore.utils.MailUtils.sendMail(MailUtils.java:50) at cn.itcast.estore.service.UserServiceImpl.regist(UserServiceImpl.java:33) at cn.itcast.estore.web.servlet.UsersServlet.regist(UsersServlet.java:78) at cn.itcast.estore.web.servlet.UsersServlet.doGet(UsersServlet.java:32) at cn.itcast.estore.web.servlet.UsersServlet.doPost(UsersServlet.java:98) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) Caused by: java.net.UnknownHostException: smtp.qq.com at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366) at java.net.Socket.connect(Socket.java:519) at java.net.Socket.connect(Socket.java:469) at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288) at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231) at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900) ... 25 more 这是我写的一个工具类代码: public class MailUtils { public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException { // 1.创建一个程序与邮件服务器会话对象 Session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP"); props.setProperty("mail.host", "smtp.qq.com"); props.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("312476956@qq.com", "SN19900103"); } }; Session session = Session.getInstance(props, auth); // 2.创建一个Message,它相当于是邮件内容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("312476956@qq.com")); // 设置发送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者 message.setSubject("用户激活"); // message.setText("这是一封激活邮件,请<a href='#'>点击</a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.创建 Transport用于将邮件发送 Transport.send(message); } } 求大神们帮忙看一下?我感觉代码应该是没问题,是不是我哪里没开启什么服务还是什么其他的问题?
axis接口部署到linux 下调用不了,但可以访问wsdl文件。 调用时候会报以下错误
[cmall] DEBUG [http-bio-8080-exec-10] SimpleChain.invoke(86) | Exit: SimpleChain::invoke [cmall] DEBUG [http-bio-8080-exec-10] NetworkUtils.getLocalHostname(76) | Failed to lookup local IP address java.net.UnknownHostException: sitxs.credit: sitxs.credit at java.net.InetAddress.getLocalHost(InetAddress.java:1402) at org.apache.axis.utils.NetworkUtils.getLocalHostname(NetworkUtils.java:65) at org.apache.axis.AxisFault.addHostnameIfNeeded(AxisFault.java:908) at org.apache.axis.AxisFault.initFromException(AxisFault.java:290) at org.apache.axis.AxisFault.<init>(AxisFault.java:184) at org.apache.axis.AxisFault.makeFault(AxisFault.java:104) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:407) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:689) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:662) AxisFault faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException faultSubcode: faultString: java.lang.NullPointerException faultActor: faultNode: faultDetail: {http://xml.apache.org/axis/}stackTrace:java.lang.NullPointerException at org.apache.axis.wsa.UUIDGenerator.getUUID(UUIDGenerator.java:58) at org.apache.axis.wsa.MIHeader.&lt;init&gt;(MIHeader.java:74) at org.apache.axis.wsa.MIHeader.fromRequest(MIHeader.java:130) at org.apache.axis.wsa.WSAHandler.processServerRequest(WSAHandler.java:90) at org.apache.axis.wsa.WSAHandler.invoke(WSAHandler.java:44) at org.apache.axis.server.AxisServer.invokeService(AxisServer.java:187) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:375) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:689) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:662) {http://xml.apache.org/axis/}hostname:127.0.0.1 java.lang.NullPointerException at org.apache.axis.AxisFault.makeFault(AxisFault.java:104) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:407) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:689) at javax.servlet.http.HttpServlet.service(HttpServlet.java:646) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:727) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:662)
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个内存泄漏。。。。。然后宕机 重启下就好了 然后一段时间后还是重复
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服务端返回的信息,代码如下,这个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广播相关问题,我到底应该使用什么广播地址才可以发送广播消息。谢谢
网上查询关于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.*.*无法收到广播包。谢谢
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写的客户端发送数据失败!!
连接时,给服务端发送数据时总是报错!! 11-28 11:15:36.164: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true 11-28 11:15:36.164: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1 11-28 11:15:36.164: W/System.err(4212): java.net.SocketException: Socket is closed 11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675) 11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415) 11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104) 11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410) 11-28 11:15:36.174: W/System.err(4212): at java.lang.Thread.run(Thread.java:841) 11-28 11:15:38.194: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true 11-28 11:15:38.194: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1 11-28 11:15:38.194: W/System.err(4212): java.net.SocketException: Socket is closed 11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675) 11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415) 11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104) 11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410) 11-28 11:15:38.204: W/System.err(4212): at java.lang.Thread.run(Thread.java:841) 客户端代码为: package cn.LCSys.socket; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import cn.LCSys.MainActivity; import cn.LCSys.fragment.SystemSetting; import android.content.Intent; import android.os.SystemClock; import android.util.Log; public class TCPClient { private String TAG = "TCP Client"; private static TCPClient s_Tcp = null; // 要连接的服务器Ip地址 private String SrvIp; // 要连接的远程服务器在监听的端口 private int SrvPort; public boolean isInitialized = false; private boolean bConnect; Socket socket = null ; private long LastTickCount; public static synchronized TCPClient instance() { if (s_Tcp == null) { { s_Tcp = new TCPClient(Const.SOCKET_SERVER, Const.SOCKET_PORT); } } return s_Tcp; } public TCPClient(String HostIp, int HostListenningPort) { LastTickCount = 0; Log.d(TAG,"SrvIP:["+HostIp+"]SrvPort:["+HostListenningPort+"]."); this.SrvIp = HostIp; this.SrvPort = HostListenningPort; bConnect = false; try { start(); } catch (Exception e) { this.isInitialized = false; Log.d(TAG," TCPClient Initialize catch err!"+e.getMessage()); e.printStackTrace(); } } public static final Object locked = new Object(); public static final BlockingQueue<String> queue = new ArrayBlockingQueue<String>( 1024 * 100); //通过数据接收判断是否链路正常 10秒没有数据认为链路异常,进行重新连接 class EchoThread extends Thread{ private Socket socket; @Override public void run() { while(isInitialized){ try { if(LastTickCount > 0) { //10 if((System.currentTimeMillis() - LastTickCount) > Const.SOCKET_TIMOUT) { bConnect = false; LastTickCount = 0; } } SystemClock.sleep(500); } catch (Exception e) { e.printStackTrace(); } } } } //发送数据 public boolean sendMsg(String sendMsg) throws InterruptedException{ try { PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); pw.write(sendMsg); pw.flush(); return true; } catch (Exception e) { bConnect = false; e.printStackTrace(); return false; } } //} // 接收数据的线程 class ReceiveThread extends Thread { private Socket socket; public ReceiveThread(Socket socket) { this.socket = socket; } @Override public void run() { String receivedString; CharBuffer charBuffer = CharBuffer.allocate(4096); while(isInitialized){ try { Reader reader = new InputStreamReader(socket.getInputStream()); charBuffer.clear(); int index = -1; while((index=reader.read(charBuffer))!=-1) { LastTickCount = System.currentTimeMillis(); charBuffer.flip(); //System.out.println("client:"+charBuffer.toString()); Charset cs = Charset.forName("UTF-8"); receivedString = cs.encode(charBuffer).toString() ; int readlen = receivedString.length(); if( readlen > 100) { //无法获取到数据 /*receivedString = Charset.forName("US-ASCII") .newDecoder().decode(buffer).toString();*/ // mylcHandle.ColldataHandle(receivedString); Log.d(TAG,"Read Data Length: "+readlen); } else { Log.d(TAG, "Recv len:"+readlen+" Content:"+receivedString); } Intent i = new Intent(Const.BC);//广播消息,实现类之间的交互 i.putExtra("response", receivedString); MainActivity.s_context.sendBroadcast(i); //给系统配置广播数据 if(null!= SystemSetting.s_context) { Log.d(TAG, "Broad to SystemSetting:"+readlen); SystemSetting.s_context.sendBroadcast(i); } //给实时数据fragement广播数据 /* if(null!= FragmentRealData.s_context) { Intent ii = new Intent(Const.DATABC); ii.putExtra("response", receivedString); Log.d(TAG, "Broad to FragmentRealData:"+readlen); FragmentRealData.s_context.sendBroadcast(ii); }*/ charBuffer.clear(); } } catch (Exception e) { e.printStackTrace(); } } } } public void start() throws UnknownHostException, IOException{ socket = new Socket(SrvIp,SrvPort); if(socket != null) { bConnect = true; isInitialized = true; new ReceiveThread(socket).start(); } else { bConnect = false; } } boolean isConnect() { return bConnect; } public void closeTCPSocket() { try{ if(socket!= null) { socket.close(); isInitialized = false; } } catch(Exception ex) { Log.e(TAG,"Close Socket error!"); } } // public static void main(String[] args) throws UnknownHostException, IOException { // new TCPClient().start(); // } }
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学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、PDF搜索网站推荐 对于大部
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 顺便拉下票,我在参加csdn博客之星竞选,欢迎投票支持,每个QQ或者微信每天都可以投5票,扫二维码即可,http://m234140.nofollow.ax.
Vue + Spring Boot 项目实战(十四):用户认证方案与完善的访问拦截
本篇文章主要讲解 token、session 等用户认证方案的区别并分析常见误区,以及如何通过前后端的配合实现完善的访问拦截,为下一步权限控制的实现打下基础。
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入  假设现有4个人
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 欢迎 改进 留言。 演示地点跳到演示地点 html代码如下`&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;music&lt;/title&gt; &lt;meta charset="utf-8"&gt
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。 1. for - else 什么?不是 if 和 else 才
数据库优化 - SQL优化
前面一篇文章从实例的角度进行数据库优化,通过配置一些参数让数据库性能达到最优。但是一些“不好”的SQL也会导致数据库查询变慢,影响业务流程。本文从SQL角度进行数据库优化,提升SQL运行效率。 判断问题SQL 判断SQL是否有问题时可以通过两个表象进行判断: 系统级别表象 CPU消耗严重 IO等待严重 页面响应时间过长
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 c/c++ 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7
通俗易懂地给女朋友讲:线程池的内部原理
餐厅的约会 餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”我楞了一下,心里想女朋友今天是怎么了,怎么突然问出这么专业的问题,但做为一个专业人士在女朋友面前也不能露怯啊,想了一下便说:“我先给你讲讲我前同事老王的故事吧!” 大龄程序员老王 老王是一个已经北漂十多年的程序员,岁数大了,加班加不动了,升迁也无望,于是拿着手里
经典算法(5)杨辉三角
写在前面: 我是 扬帆向海,这个昵称来源于我的名字以及女朋友的名字。我热爱技术、热爱开源、热爱编程。技术是开源的、知识是共享的。 这博客是对自己学习的一点点总结及记录,如果您对 Java、算法 感兴趣,可以关注我的动态,我们一起学习。 用知识改变命运,让我们的家人过上更好的生活。 目录一、杨辉三角的介绍二、杨辉三角的算法思想三、代码实现1.第一种写法2.第二种写法 一、杨辉三角的介绍 百度
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹
面试官:你连RESTful都不知道我怎么敢要你?
面试官:了解RESTful吗? 我:听说过。 面试官:那什么是RESTful? 我:就是用起来很规范,挺好的 面试官:是RESTful挺好的,还是自我感觉挺好的 我:都挺好的。 面试官:… 把门关上。 我:… 要干嘛?先关上再说。 面试官:我说出去把门关上。 我:what ?,夺门而去 文章目录01 前言02 RESTful的来源03 RESTful6大原则1. C-S架构2. 无状态3.统一的接
SQL-小白最佳入门sql查询一
一 说明 如果是初学者,建议去网上寻找安装Mysql的文章安装,以及使用navicat连接数据库,以后的示例基本是使用mysql数据库管理系统; 二 准备前提 需要建立一张学生表,列分别是id,名称,年龄,学生信息;本示例中文章篇幅原因SQL注释略; 建表语句: CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // dosho
漫话:什么是平衡(AVL)树?这应该是把AVL树讲的最好的文章了
这篇文章通过对话的形式,由浅入深带你读懂 AVL 树,看完让你保证理解 AVL 树的各种操作,如果觉得不错,别吝啬你的赞哦。 1、若它的左子树不为空,则左子树上所有的节点值都小于它的根节点值。 2、若它的右子树不为空,则右子树上所有的节点值均大于它的根节点值。 3、它的左右子树也分别可以充当为二叉查找树。 例如: 例如,我现在想要查找数值为14的节点。由于二叉查找树的特性,我们可...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,
程序员:我终于知道post和get的区别
IT界知名的程序员曾说:对于那些月薪三万以下,自称IT工程师的码农们,其实我们从来没有把他们归为我们IT工程师的队伍。他们虽然总是以IT工程师自居,但只是他们一厢情愿罢了。 此话一出,不知激起了多少(码农)程序员的愤怒,却又无可奈何,于是码农问程序员。 码农:你知道get和post请求到底有什么区别? 程序员:你看这篇就知道了。 码农:你月薪三万了? 程序员:嗯。 码农:你是怎么做到的? 程序员:
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU
开源并不是你认为的那些事
点击上方蓝字 关注我们开源之道导读所以 ————想要理清开源是什么?先要厘清开源不是什么,名正言顺是句中国的古代成语,概念本身的理解非常之重要。大部分生物多样性的起源,...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
      11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1
程序员把地府后台管理系统做出来了,还有3.0版本!12月7号最新消息:已在开发中有github地址
第一幕:缘起 听说阎王爷要做个生死簿后台管理系统,我们派去了一个程序员…… 996程序员做的梦: 第一场:团队招募 为了应对地府管理危机,阎王打算找“人”开发一套地府后台管理系统,于是就在地府总经办群中发了项目需求。 话说还是中国电信的信号好,地府都是满格,哈哈!!! 经常会有外行朋友问:看某网站做的不错,功能也简单,你帮忙做一下? 而这次,面对这样的需求,这个程序员
网易云6亿用户音乐推荐算法
网易云音乐是音乐爱好者的集聚地,云音乐推荐系统致力于通过 AI 算法的落地,实现用户千人千面的个性化推荐,为用户带来不一样的听歌体验。 本次分享重点介绍 AI 算法在音乐推荐中的应用实践,以及在算法落地过程中遇到的挑战和解决方案。 将从如下两个部分展开: AI 算法在音乐推荐中的应用 音乐场景下的 AI 思考 从 2013 年 4 月正式上线至今,网易云音乐平台持续提供着:乐屏社区、UGC
【技巧总结】位运算装逼指南
位算法的效率有多快我就不说,不信你可以去用 10 亿个数据模拟一下,今天给大家讲一讲位运算的一些经典例子。不过,最重要的不是看懂了这些例子就好,而是要在以后多去运用位运算这些技巧,当然,采用位运算,也是可以装逼的,不信,你往下看。我会从最简单的讲起,一道比一道难度递增,不过居然是讲技巧,那么也不会太难,相信你分分钟看懂。 判断奇偶数 判断一个数是基于还是偶数,相信很多人都做过,一般的做法的代码如下
《C++ Primer》学习笔记(六):C++模块设计——函数
专栏C++学习笔记 《C++ Primer》学习笔记/习题答案 总目录 https://blog.csdn.net/TeFuirnever/article/details/100700212 —————————————————————————————————————————————————————— 《C++ Primer》习题参考答案:第6章 - C++模块设计——函数 文章目录专栏C+...
8年经验面试官详解 Java 面试秘诀
    作者 | 胡书敏 责编 | 刘静 出品 | CSDN(ID:CSDNnews) 本人目前在一家知名外企担任架构师,而且最近八年来,在多家外企和互联网公司担任Java技术面试官,前后累计面试了有两三百位候选人。在本文里,就将结合本人的面试经验,针对Java初学者、Java初级开发和Java开发,给出若干准备简历和准备面试的建议。   Java程序员准备和投递简历的实
面试官如何考察你的思维方式?
1.两种思维方式在求职面试中,经常会考察这种问题:北京有多少量特斯拉汽车? 某胡同口的煎饼摊一年能卖出多少个煎饼? 深圳有多少个产品经理? 一辆公交车里能装下多少个乒乓球? 一
so easy! 10行代码写个"狗屁不通"文章生成器
前几天,GitHub 有个开源项目特别火,只要输入标题就可以生成一篇长长的文章。背后实现代码一定很复杂吧,里面一定有很多高深莫测的机器学习等复杂算法不过,当我看了源代码之后这程序不到50
知乎高赞:中国有什么拿得出手的开源软件产品?(整理自本人原创回答)
知乎高赞:中国有什么拿得出手的开源软件产品? 在知乎上,有个问题问“中国有什么拿得出手的开源软件产品(在 GitHub 等社区受欢迎度较好的)?” 事实上,还不少呢~ 本人于2019.7.6进行了较为全面的 回答 - Bravo Yeung,获得该问题下回答中得最高赞(236赞和1枚专业勋章),对这些受欢迎的 Github 开源项目分类整理如下: 分布式计算、云平台相关工具类 1.SkyWalk
相关热词 c# 引用mysql c#动态加载非托管dll c# 两个表数据同步 c# 返回浮点json c# imap 链接状态 c# 漂亮字 c# 上取整 除法 c#substring c#中延时关闭 c#线段拖拉
立即提问