DatagramChannel在connect后如何正确的用read和write方法来收发消息

想试试DatagramChannel的write和read方法是否可以收发信息。

public class DatagramChannelExer3 {
    public static void main(String[] args) throws InterruptedException{
        Thread server = new Thread(new Server3());
        server.start();
        
        Thread.sleep(1000);
        
        Thread client = new Thread(new Client3());
        client.start();
        
    }
}

class Server3 implements Runnable{

    @Override
    public void run() {        
        try {
            DatagramChannel dc = DatagramChannel.open();
            SocketAddress sc = new InetSocketAddress("localhost", 9988); 
            //不采取bind的方式,而是改为connect的方式
            dc.connect(sc);
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            
            System.out.println(dc.isConnected());
            while(true){
                int length = dc.read(buffer);
                System.out.println(length);
                
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}

class Client3 implements Runnable{

    @Override
    public void run() {
        try {
            DatagramChannel dc = DatagramChannel.open();
            
            SocketAddress connectAddress = new InetSocketAddress("localhost", 9988);
            
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            
            dc.connect(connectAddress);
            buffer.put("hello world".getBytes());
            buffer.flip();
            
            dc.write(buffer);
            
            //关闭通道
            dc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
}

但是程序一直在read的方法出被阻塞,获取不到任何消息,想问如果利用read和write方法来收发消息的话,正确的写法应该是怎样的。
求各位大神帮助,谢谢!

阅读 4.8k
2 个回答

我倒是很少用这个类,但是我就想知道server为什么是用connect而不是用bind?除去读写的部分你没发现你server和client的代码都一样的么?

新手上路,请多包涵

刚刚看书,好奇书上的代码怎么用了connect,没有bind本地端口。connect的参数是远端socke地址,不是这个channel的本地socket地址,我猜调用conncet自动分配的匿名的本地地址。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题