我正在编写一组Client/Server程序
根据客户端请求的操作,我使用make TCP或UDP请求.
实现客户端是直截了当的,因为我可以轻松地打开与任何协议的连接并将请求发送到服务器端.
另一方面,在服务器端,我想在同一端口上同时监听UDP和TCP连接.而且,我喜欢服务器为每个连接请求打开新线程.
我采用了以下解释的方法:链接文本
我通过为每个TCP/UDP请求创建新线程来扩展此代码示例.
如果我只使用TCP,这可以正常工作,但是当我尝试进行UDP绑定时它会失败.
请给我任何建议如何纠正这个问题.
TNX
这是服务器代码:
public class Server {
public static void main(String args[]) {
try {
int port = 4444;
if (args.length > 0)
port = Integer.parseInt(args[0]);
SocketAddress localport = new InetSocketAddress(port);
// Create and bind a tcp channel to listen for connections on.
ServerSocketChannel tcpserver = ServerSocketChannel.open();
tcpserver.socket().bind(localport);
// Also create and bind a DatagramChannel to listen on.
DatagramChannel udpserver = DatagramChannel.open();
udpserver.socket().bind(localport);
// Specify non-blocking mode for both channels, since …Run Code Online (Sandbox Code Playgroud)