Java教程

网络编程多线程在线咨询

本文主要是介绍网络编程多线程在线咨询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在线咨询:两个人都是发送方,也是接收方。

先编写发送信息代码

public class TalkSend implements Runnable {
    DatagramSocket socket = null;
    BufferedReader reader = null;

     private int fromPort;
     private String toIP;
     private int toPort;

    public TalkSend(int fromPort, String toIP, int toPort) {
        this.fromPort = fromPort;
        this.toIP = toIP;
        this.toPort = toPort;

        try{
            socket = new DatagramSocket(fromPort);
            //准备数据 控制台读取 System.in
            reader = new BufferedReader(new InputStreamReader(System.in));
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true){

            try {
                String data = reader.readLine();
                byte[] bytes = data.getBytes();
                DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,new InetSocketAddress(this.toIP,this.toPort));

                socket.send(packet);
                if (data.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        socket.close();
    }
}

然后编写接收信息代码

public class TalkReceive implements Runnable{
    DatagramSocket socket = null;

    private int port;
    private String name;

    public TalkReceive(int port,String name) {
        this.port = port;
        this.name = name;

        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(name+":"+receiveData);

                if (receiveData.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        socket.close();
    }
}

最后是学生和老师端

public class TalkStudent {
    public static void main(String[] args) {
        //开启两个线程
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkReceive(8888,"老师")).start();
    }
}
public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkReceive(9999,"学生")).start();
    }
}

这样便可以实现信息互通

这篇关于网络编程多线程在线咨询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!