在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java  網(wǎng)絡(luò)安全  HTML/ DatagramChannel在connect后如何正確的用read和write

DatagramChannel在connect后如何正確的用read和write方法來收發(fā)消息

想試試DatagramChannel的write和read方法是否可以收發(fā)信息。

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);
            //創(chuàng)建緩沖區(qū)
            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);
            
            //關(guān)閉通道
            dc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
    
}

但是程序一直在read的方法出被阻塞,獲取不到任何消息,想問如果利用read和write方法來收發(fā)消息的話,正確的寫法應(yīng)該是怎樣的。
求各位大神幫助,謝謝!

回答
編輯回答
舊時(shí)光

我倒是很少用這個(gè)類,但是我就想知道server為什么是用connect而不是用bind?除去讀寫的部分你沒發(fā)現(xiàn)你server和client的代碼都一樣的么?

2018年1月17日 22:32