练习篇------面向对象之 Udp实现老师学生在线聊天

32 篇文章 0 订阅
11 篇文章 0 订阅

共需要四个类

  • 消息发送类
  • 消息接收类
  • 老师类
  • 学生类

这里用到了多线程

  • 消息发送类
public class UdpTalkSend implements Runnable{
    DatagramSocket socket =null;
    BufferedReader reader = null;
    int fromPort;
    String toIP;
    int toPort;

    public UdpTalkSend(int fromPort,String toIP,int toPort) {
        this.fromPort=fromPort;
        this.toIP=toIP;
        this.toPort=toPort;
        try{
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    @Override
    public void run() {
        while(true){
            try {
                String data=reader.readLine();
                byte[] datas = data.getBytes();
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIP, this.toPort));

                socket.send(packet);
                if(data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
  • 消息接收类
public class UdpTalkReceive implements Runnable{
    DatagramSocket socket =null;
    int port;
    String msgFrom;

    public UdpTalkReceive(int port,String msgFrom) {
        this.port = port;
        this.msgFrom=msgFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while(true){
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet);

                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom+":"+receiveData);
                if(receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        socket.close();
    }
}
  • 学生类
public class UdpTalkStudent {
    public static void main(String[] args) {
        new Thread(new UdpTalkSend(6666,"localhost",8888)).start();
        new Thread(new UdpTalkReceive(9999,"学生")).start();
    }
}
  • 老师类
public class UdpTalkTeacher {
    public static void main(String[] args) {
        new Thread(new UdpTalkSend(7777,"localhost",9999)).start();
        new Thread(new UdpTalkReceive(8888,"老师")).start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值