UDP聊天实现(包含多线程)

UDP实现聊天分为单向通信,和双向通信。

单向通信,只能由客户端向服务器发送消息:

客户端代码

package UDP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;

//不需要连接服务器
public class UDPclient {
    public static void main(String args[]) throws Exception {
        //1.建立一个socket
        DatagramSocket socket = new DatagramSocket(8080);
        //2.建个包
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            String data = reader.readLine();

            byte[] datas = data.getBytes(StandardCharsets.UTF_8);

            InetAddress ip = InetAddress.getByName("localhost");
            // 3.数据, 数据的长度,发送给谁
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, ip, 6666);

            //4.发送
            socket.send(packet);
            if(data.equals("bye"))
            {
                break;
            }
        }

        //关闭
        socket.close();

    }
}

服务器代码

package UDP;

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 UDPserver {
    public static  void main(String  args[]) throws IOException {
        //开放端口
        DatagramSocket socket = new DatagramSocket(6666);

        //接受数据包
        while (true) {
            //准备接受包裹
            byte[] b = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(b, 0, b.length);
            socket.receive(datagramPacket);
            //断开连接
            byte [] data= datagramPacket.getData();

            String str = new String(data,0,data.length);
            //trim 去除数据后面的空格
            System.out.println(str.trim());

            if (str.equals("bye"))
            {
                break;
            }
            //阻塞接受
        }

        //关闭连接
       socket.close();


    }
}

双向通信(多线程),双方都可以发送和接受消息

发送消息线程

package UDP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;

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

    private String toip;
    private  int toport;
    private  int fromport;


    public sendthread(String toip, int toport, int fromiort) throws Exception {

        this.toip = toip;
        this.toport = toport;
        this.fromport = fromport;

        socket = new DatagramSocket(fromport);
        reader = new BufferedReader(new InputStreamReader(System.in));


    }

    @Override
    public void run() {
        while (true) {
            String data = null;
            try {
                data = reader.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }

            byte[] datas = data.getBytes(StandardCharsets.UTF_8);

            try {
                InetAddress ip = InetAddress.getByName("localhost");
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            // 3.数据, 数据的长度,发送给谁
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toip,this.toport));

            //4.发送
            try {
                socket.send(packet);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(data.equals("bye"))
            {
                break;
            }
        }

    }
}

接受消息线程

package UDP;

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

public class receivethread implements  Runnable{
    DatagramSocket socket=null;
    private  int port;
    private  String msgfrom;

    public  receivethread(int port, String msgfrom) throws Exception {

        this.port = port;
        this.msgfrom = msgfrom;
        socket = new DatagramSocket(this.port);

    }

    @Override
    public void run() {
        //开放端口

        //接受数据包
        while (true) {
            //准备接受包裹
            byte[] b = new byte[1024];
            DatagramPacket datagramPacket = new DatagramPacket(b, 0, b.length);
            try {
                socket.receive(datagramPacket);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //断开连接
            byte [] data= datagramPacket.getData();

            String str = new String(data,0,data.length);
            //trim 去除数据后面的空格
            System.out.println(this.msgfrom+":"+str.trim());

            if (str.equals("bye"))
            {
                break;
            }
            //阻塞接受
        }
    }
}

接受消息线程和接受消息线程都有,只需建立两个主类同时开启两个线程即可以实现通信聊天。

package UDP;

public class zhanghen {
    public  static  void  main(String args[]) throws Exception {

        new Thread(new sendthread("localhost", 8888, 9999)).start();
        new Thread(new receivethread(5555,"zhengshuang")).start();
    }
}
package UDP;

public class zhenshuang {
    public  static  void  main(String args[]) throws Exception {

        new Thread(new sendthread("localhost", 5555, 6666)).start();
        new Thread(new receivethread(8888,"zhanghen")).start();
    }
}

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值