我是新来的。 我是一名 Java 开发人员(新手),目前我正在从事 BSE 项目,我面临着从服务器(服务器套接字)读取客户端(客户端套接字)上的字节包的问题。如果你能帮助我,请帮助我。
提前致谢
最佳答案
好吧,如果你想直接与数据包交互,那么你需要使用 DatagramSocket
而不是常规的 Socket 和 ServerSocket。
那么,你应该visit this link查看有关如何开始发送和接收单个数据包的好教程。
基本思想是,客户端或服务器在等待其伙伴使用 send()
发送数据包时,将阻塞 recieve()
调用。
如果您对问题中指出的单个数据包不感兴趣,那么您将需要使用 Socket
和 ServerSocket
。两者之间进行通信的第一步涉及类似于以下内容的代码:
//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
}
客户端和服务器将需要类似的循环。
关于java - 使用java从服务器(ServerSocket)读取客户端(客户端Socket)上的字节包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3659318/