问题描述
importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.InputStreamReader;importjava.io.OutputStreamWriter;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassServerimplementsRunnable{publicvoidrun(){try{ServerSocketserverSocket=newServerSocket(51706);while(true){System.out.println("loading");Socketsocket=serverSocket.accept();System.out.println("accept");try{BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(socket.getInputStream()));Stringstr=bufferedReader.readLine();System.out.println("read:"+str);PrintWriterprintWriter=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);System.out.println("servermessage");bufferedReader.close();printWriter.close();}catch(Exceptione){//TODO:handleexceptionSystem.out.println(e.getMessage());e.printStackTrace();}finally{socket.close();System.out.println("close");}}}catch(Exceptione){//TODO:handleexceptionSystem.out.println(e.getMessage());}}/***@paramargs*/publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubThreadthread=newThread(newServer());thread.start();}}编译后运行只打印出loading然后就卡死查询端口结果TCP[::]:51706[::]:0LISTENING0
解决方案
解决方案二:
卡死?哈哈.其实一点不卡的.正如你端口查询结果一样,一直监听那些来连接这个serverSocket.你这里仅仅生成了一个ServerSocket,这相当于服务器,他们的任务是等待Socket.所以你要另外生成一个socket=newSocket("127.0.0.1",51706);
解决方案三:
还需要一个客户端socket比如客户端socket应该这样写ClientSocket{Socketsocket=newSocket("127.0.0.1",51706);}服务端socket应该这样写ServerSocket{ServerSocketserverSocket=newServerSocket(51706);Socketsocket=serverSocket.accept();}
解决方案四:
Socketsocket=serverSocket.accept();serveraccept后,一定要新起线程去处理数据交流..否则程序不继续,后面的client连接就不能处理了。