UDP在线咨询(面向对象的思想)

1)发送端 

package com.sxt.udp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;

public class TalkClient implements Runnable{
    private DatagramSocket client;
    private BufferedReader reader;
    private String toIP;
    private int toPort;
    public TalkClient(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() {
        String msg;
        while(true){
            try {
                msg= reader.readLine();
                byte[] data=msg.getBytes();
                DatagramPacket dp = new DatagramPacket(data, 0, data.length, new InetSocketAddress(this.toIP, this.toPort));
                client.send(dp);
                if(msg.equals("bye")) break;

            } catch (IOException e) {
                e.printStackTrace();
            }

            }
        client.close();
        }

    }

 2)接收端

package com.sxt.udp;

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

public class TalkServer implements Runnable{
    private  DatagramSocket server;

    public TalkServer(int port) {
        try {
            server= new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }
    
    @Override
    public void run() {
        
    while (true){
        byte[] container = new byte[1024 * 60];
        DatagramPacket packet = new DatagramPacket(container, 0, container.length);
        try {
            server.receive(packet);
            byte[] datas = packet.getData();
            int len = packet.getLength();
            String msg=new String(datas,0,datas.length);
            System.out.println(msg);
            if(msg.equals("bye")){
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

        server.close();
    }
}

3)学生端(可接收与发送) 

package com.sxt.udp;

public class TalkStudent {
    public static void main(String[] args) {
        new Thread(new TalkClient(8888,"localhost",6666)).start();
        new Thread(new TalkServer(7777)).start();
    }
}

 4)老师端(可接收与发送)

package com.sxt.udp;

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkServer(6666)).start();
        new Thread(new TalkClient(5555,"localhost",7777)).start();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值