当前位置:  开发笔记 > 编程语言 > 正文

在同一端口上侦听TCP和UDP请求

如何解决《在同一端口上侦听TCP和UDP请求》经验,为你挑选了0个好方法。

我正在编写一组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 our
        // Selector object will be doing the blocking for us.
        tcpserver.configureBlocking(false);
        udpserver.configureBlocking(false);

        // The Selector object is what allows us to block while waiting
        // for activity on either of the two channels.
        Selector selector = Selector.open();

        tcpserver.register(selector, SelectionKey.OP_ACCEPT);
        udpserver.register(selector, SelectionKey.OP_READ);

        System.out.println("Server Sterted on port: " + port + "!");

        //Load Map
        Utils.LoadMap("mapa");
        System.out.println("Server map ... LOADED!");

        // Now loop forever, processing client connections
        while(true) {
            try { 
                selector.select();
                Set keys = selector.selectedKeys();

                // Iterate through the Set of keys.
                for (Iterator i = keys.iterator(); i.hasNext();) {
                    SelectionKey key = i.next();
                    i.remove();

                    Channel c = key.channel();

                    if (key.isAcceptable() && c == tcpserver) {
                        new TCPThread(tcpserver.accept().socket()).start();
                    } else if (key.isReadable() && c == udpserver) {
                        new UDPThread(udpserver.socket()).start();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e);
        System.exit(1);
    }
}

}

UDPThread代码:

public class UDPThread extends Thread {
private DatagramSocket socket = null;

public UDPThread(DatagramSocket socket) {
    super("UDPThread");
    this.socket = socket;
}

@Override
public void run() {
    byte[] buffer = new byte[2048];
    try {           
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        socket.receive(packet);

        String inputLine = new String(buffer);
        String outputLine = Utils.processCommand(inputLine.trim());

        DatagramPacket reply = new DatagramPacket(outputLine.getBytes(), outputLine.getBytes().length,
                                                  packet.getAddress(), packet.getPort());
        socket.send(reply);

    } catch (IOException e) {
        e.printStackTrace();
    }
    socket.close(); 
}

}

我收到:

Exception in thread "UDPThread" java.nio.channels.IllegalBlockingModeException
at sun.nio.ch.DatagramSocketAdaptor.receive(Unknown Source)
at server.UDPThread.run(UDPThread.java:25)

10倍

推荐阅读
wangtao
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有