问题描述
服务端:packageSocketTest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;publicclassServer{publicstaticvoidmain(String[]args){ServerSocketserver=null;try{server=newServerSocket(4700);}catch(IOExceptione){//TODOAuto-generatedcatchblockSystem.out.println("Cantlistento:"+e);}Socketsocket=null;try{socket=server.accept();}catch(IOExceptione){//TODOAuto-generatedcatchblockSystem.out.println("Error."+e);}Stringline;BufferedReaderis;try{is=newBufferedReader(newInputStreamReader(socket.getInputStream()));PrintWriteros=newPrintWriter(socket.getOutputStream());BufferedReadersin=newBufferedReader(newInputStreamReader(System.in));System.out.println("Client."+is.readLine());line=sin.readLine();ThreadserverListener=newThread(newServerListener());serverListener.start();while(!line.equals("bye")){os.println(line);os.flush();System.out.println("Server:"+line);System.out.println("Client:"+is.readLine());line=sin.readLine();}os.close();is.close();socket.close();server.close();}catch(IOExceptione){System.out.println("Error."+e);}}}
客户端:packageSocketTest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.net.UnknownHostException;publicclassClient{publicstaticvoidmain(String[]args){try{//向本机的4700端口发出客户请求Socketsocket=newSocket("127.0.0.1",4700);//由系统标准输入设备构造BufferedReader对象BufferedReadersin=newBufferedReader(newInputStreamReader(System.in));//由socket对象得到输入流,并构造PrintWriter对象PrintWriteros=newPrintWriter(socket.getOutputStream());BufferedReaderis=newBufferedReader(newInputStreamReader(socket.getInputStream()));Stringreadline;readline=sin.readLine();while(!readline.equals("bye")){os.println(readline);os.flush();System.out.println("Client:"+readline);System.out.println("Server:"+is.readLine());readline=sin.readLine();}os.close();is.close();socket.close();}catch(IOExceptione){System.out.println("Error"+e);}}}
在测试的时候,客户端发送消息到服务端,第一次可以即时发送,第二次发送后,必须服务端返回消息给客户端才可以继续显示,有没有什么办法可以监听socket的数据变化?头大,各位大大赐教
解决方案
解决方案二:
这是Java老的Socket编程API,你看一下新的javaNIOAPI,里面已经用selector和监听机制了,且管道不仅仅是socket还有文件等channel类型,开发你的需求简单多了
解决方案三:
引用1楼qingyuan18的回复:
这是Java老的Socket编程API,你看一下新的javaNIOAPI,里面已经用selector和监听机制了,且管道不仅仅是socket还有文件等channel类型,开发你的需求简单多了
用老的可以搞定这个问题吗
解决方案四:
有朋友在吗?现在又遇到这个问题,很苦恼packageSocketTest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.ArrayList;importjava.util.List;publicclassServer{privatestaticList<Socket>sockes=null;privatestaticServerinstance;publicServer(){sockes=newArrayList<Socket>();}publicstaticvoidmain(String[]args){ServerSocketserver=null;try{server=newServerSocket(4700);}catch(IOExceptione){//TODOAuto-generatedcatchblockSystem.out.println("Cantlistento:"+e);}Socketsocket=null;try{while(true){socket=server.accept();Threadthread=newThread(newServerListener(socket));thread.start();System.out.println("NewThreadStarted");}}catch(IOExceptione){System.out.println("Error."+e);}}publicstaticvoidaddSocket(intposition,Sockets){sockes.add(position,s);}publicstaticvoidprint(Objecto){System.out.println(o);}publicstaticSocketgetSocket(intposition){returnsockes.get(position);}}
packageSocketTest;importjava.io.BufferedInputStream;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;publicclassServerListenerimplementsRunnable{privateSocketsocket=null;/**用来读取客户端发送的消息*/privateBufferedReaderis=null;/**用来给客户端发送消息*/privatePrintWriterout=null;/**客户端发送的消息*/privateStringline=null,SEND_OBJECT=null;/**用来保存Socket线程ID*/publicstaticintSocket_ID;/**用来给指定的其他客户端发送消息*/privatePrintWriteroutTo;/**保存初识信息**/privateStringtext;publicServerListener(Socketsocket){this.socket=socket;//System.out.println("Sorry");}@Overridepublicvoidrun(){try{is=newBufferedReader(newInputStreamReader(socket.getInputStream()));out=newPrintWriter(socket.getOutputStream());text=is.readLine();System.out.println(text);Socket_ID=Integer.valueOf(newString(text.getBytes()).trim().split(",")[0]);SEND_OBJECT=newString(text.getBytes()).trim().split(",")[1];System.out.println(Socket_ID);Server.addSocket(Socket_ID,socket);outTo=newPrintWriter(Server.getSocket(Integer.valueOf(SEND_OBJECT)).getOutputStream());line=is.readLine();while(!line.equals("bye")){outTo.write(line);outTo.flush();Server.print("Client"+Socket_ID+":"+line);line=is.readLine();}}catch(IOExceptione){System.out.println("Error."+e);}}}
packageSocketTest;importjava.io.BufferedReader;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintWriter;importjava.net.Socket;importjava.net.UnknownHostException;publicclassClient{publicstaticvoidmain(String[]args){StringSEND_OBJECT="1";StringClient_ID="0";try{//向本机的4700端口发出客户请求Socketsocket=newSocket("127.0.0.1",4700);//由系统标准输入设备构造BufferedReader对象BufferedReadersin=newBufferedReader(newInputStreamReader(System.in));//由socket对象得到输入流,并构造PrintWriter对象PrintWriteros=newPrintWriter(socket.getOutputStream());BufferedReaderis=newBufferedReader(newInputStreamReader(socket.getInputStream()));os.println(Client_ID+","+SEND_OBJECT);os.flush();Stringreadline;readline=sin.readLine();while(!readline.equals("bye")){os.println(readline);os.flush();System.out.println("Client:"+readline);System.out.println("Client2:"+is.readLine());readline=sin.readLine();}os.close();is.close();socket.close();}catch(IOExceptione){System.out.println("Error"+e);}}}
解决方案五:
报空指针异常,不知道是哪里有问题。Exceptioninthread"Thread-0"java.lang.NullPointerExceptionatSocketTest.Server.addSocket(Server.java:45)atSocketTest.ServerListener.run(ServerListener.java:60)atjava.lang.Thread.run(UnknownSource)
解决方案六:
ServerSocketserver=null;这句下面加上instance=newServer();错误原因是你的sockes 没有被创建。
解决方案七:
你建立的是长连接,可以在客户端如果数据更新了发送一个更新指令,你的通讯可以按照一定的格式进行组织,方便解析,然后根据对应的指令做对应的操作。
解决方案八:
发送和接收数据应该是2个独立的线程。
解决方案九:
引用5楼cjh_tostring的回复:
ServerSocketserver=null;这句下面加上instance=newServer();错误原因是你的sockes 没有被创建。
这个在下面初始化了,这个问题已经搞定了,谢谢大家。
解决方案十:
引用1楼qingyuan18的回复:
这是Java老的Socket编程API,你看一下新的javaNIOAPI,里面已经用selector和监听机制了,且管道不仅仅是socket还有文件等channel类型,开发你的需求简单多了
你好,我最近在看NIO,遇到一些问题,可以帮帮我吗?感激不尽。ScatteringReads操作的时候,我写了一个228字节的文本,用一个ByteBuffer数组读取,header读完后输出没问题,到了下一个buffer就报BufferUnderflowException错误。packagenioTest;importjava.io.File;importjava.io.IOException;importjava.io.RandomAccessFile;importjava.nio.ByteBuffer;importjava.nio.channels.FileChannel;publicclassChannelTest1{privatestaticByteBufferheader;privatestaticByteBufferbody;privatestaticFilefile;privatestaticRandomAccessFilera;privatestaticFileChannelinChannel;privatestaticlongbyteRead;publicstaticvoidmain(String[]args){file=newFile("d:"+File.separator+"text.txt");try{ra=newRandomAccessFile(file,"rw");inChannel=ra.getChannel();header=ByteBuffer.allocate(128);body=ByteBuffer.allocate(1024);ByteBuffer[]bufferArray={header,body};byteRead=inChannel.read(bufferArray);System.out.println(byteRead);//System.out.println(header.get(dst)());while(byteRead!=-1){header.flip();body.flip();while(header.hasRemaining()){byte[]dst=newbyte[128];header.get(dst);System.out.println(newString(dst));}header.compact();while(body.hasRemaining()){byte[]dst1=newbyte[128];body.get(dst1);System.out.println(newString(dst1));}byteRead=inChannel.read(bufferArray);}}catch(Exceptione){e.printStackTrace();}finally{try{ra.close();}catch(IOExceptione){e.printStackTrace();}}}}