使用java从服务器(ServerSocket)读取客户端(客户端套接字)上的字节数据包

ima新。 ima java developer(fresher),目前正在研究BSE项目,我正面临着从服务器(服务器套接字)读取客户端(客户端套接字)上的字节数据包的问题。 如果你可以帮助我那么请帮助我。

提前致谢

好吧,如果你想直接与数据包交互,那么你需要使用DatagramSocket而不是常规的SocketServerSocket

然后,您应该访问此链接以查看有关如何开始发送​​和接收单个数据包的良好教程。

基本思想是客户端或服务器在等待其伙伴使用send()发送数据包时将阻塞recieve()调用。

如果您对问题中指出的各个数据包不感兴趣,那么您将需要使用SocketServerSocket 。 两者之间进行通信的第一步涉及的代码类似于以下内容:

 //Server // this call will block until the client tries to connect to the server Socket cientConn = new ServerSocket(8878).accept(); // now you can use the connection's input and output streams to send data /******************/ // Client Socket serverConn = new Socket(addressOfServer, 8878); // now you can use the connections input and output streams 

设置连接后,基本上会有2个读/写循环。 一个在客户端上,一个在服务器上。

 while(true) [ // check for data from an input stream ... // respond with message back } 

您将需要一个类似的客户端和服务器循环。