1. 程式人生 > >多執行緒實現UDP協議傳送、接收資料

多執行緒實現UDP協議傳送、接收資料

  放碼過來吧! 

public class ChatRoom {
    public static void main(String[] args) throws SocketException {
        DatagramSocket sendSocket = new DatagramSocket();
        DatagramSocket recvSocket = new DatagramSocket(12345);
        SendThread send = new SendThread(sendSocket);
        ReceiveThread receive = new ReceiveThread(recvSocket);
        Thread sendThread = new Thread(send);
        Thread recvThread = new Thread(receive);
        sendThread.start();
        recvThread.start();
    }
}

//傳送執行緒
class SendThread implements Runnable{
    private DatagramSocket datagramSocket;
    public SendThread(DatagramSocket ds) {
        this.datagramSocket = ds;
    }
    @Override
    public void run() {
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
            String str;
            while ((str=input.readLine()) != null){
                if (str.equals("886")){
                    break;
                }
                byte[] b = str.getBytes();
                DatagramPacket packet = new DatagramPacket(b,b.length,InetAddress.getByName("172.20.0.24"),12345);
                datagramSocket.send(packet);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        datagramSocket.close();
    }
}

//接收執行緒
class ReceiveThread implements Runnable{
    private DatagramSocket datagramSocket;
    public ReceiveThread(DatagramSocket ds) {
        this.datagramSocket = ds;
    }

    @Override
    public void run() {
        try {
            while (true){
                byte[] b = new byte[1024];
                DatagramPacket packet = new DatagramPacket(b,b.length);
                datagramSocket.receive(packet);
                String ip = packet.getAddress().getHostAddress();
                String msg = new String(packet.getData(),0,packet.getLength());
                System.out.println(ip + "---接收到傳送過來的資料是:"+ msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}