1. 程式人生 > 其它 >udp程式設計:一對一諮詢

udp程式設計:一對一諮詢

package com.sundear.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 傳送端:使用面向物件封裝
 */
public class TalkSend implements
Runnable{ private DatagramSocket client; private BufferedReader reader; private String toIP; private int toPort; public TalkSend(int port,String toIP,int toPort){ this.toIP=toIP; this.toPort =toPort; try{ client = new DatagramSocket(port); reader
= new BufferedReader(new InputStreamReader(System.in)); }catch (SocketException e){ e.printStackTrace(); } } @Override public void run() { while(true) { String data; try { data = reader.readLine(); byte
[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort)); client.send(packet); if(data.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } } }
package com.sundear.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{
    private DatagramSocket server;
    private String from;
    public TalkReceive(int port,String from){
        this.from= from;
        try {
            server = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        byte[] container=new byte[1024*60];
        while(true) {
            DatagramPacket packet = new DatagramPacket(container, 0, container.length);
            try {
                server.receive(packet);
                byte[] datas = packet.getData();
                String string = new String(datas, 0, packet.getLength());
                System.out.println(this.from+":"+string);
                if(string.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        server.close();
    }
}

  

package com.sundear.demo.util;

public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkSend(7777,"localhost",9999)).start();//傳送

        new Thread(new TalkReceive(8888,"老師")).start();//接收

    }
}
package com.sundear.demo.util;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkReceive(9999,"學生")).start();//接收
        new Thread(new TalkSend(5555,"localhost",8888)).start();
    }
}

 老師和學生通過控制檯一對一聊天