UDP 服务器处理多个客户端
我创建了一个 UDP 服务器。这是一个框架
public class UDPserver {
public static void main(String[] args) throws Exception{
while(true){
.... some code ...
packet = new DatagramPacket ( data , data.length, packet.getAddress(), packet.getPort() );
.... some code ...
socket.receive( ... );
}
}
}
现在,我想让它处理多个请求,所以我检查了我必须实现 Runnable。
public class UDPserver implements Runnable { }
我读到我还需要一个 run()。但我不明白 run()。我应该将整个 while(true) 语句放在 run() 中吗? main() 呢?谁能展示如何更改上面的代码来处理多个请求? 谢谢
I created a UDP server. Here's a skeleton
public class UDPserver {
public static void main(String[] args) throws Exception{
while(true){
.... some code ...
packet = new DatagramPacket ( data , data.length, packet.getAddress(), packet.getPort() );
.... some code ...
socket.receive( ... );
}
}
}
Now, i want to make it handle multiple requests, so i checked out that i have to implement Runnable.
public class UDPserver implements Runnable { }
I read that I also need to have a run(). But i don't understand run(). should i put the whole while(true)
statement inside run()? what about main()? Can anyone show how to change my code above to handle multiple requests?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将所有代码移至 UDPServer 的 run 方法中(包括 while(true))
在您的 main 方法中:
move all the code inside the run method of UDPServer (including the while(true))
In your main method :
您还可以为每个新连接使用新线程来执行。例如:
You can also use new thread for each new connection for performing. For example: