UDP聊天实现

循环发送消息

package com.wang.netStudy.chat;

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

public class UdpSenderDemo01 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(8888);

        //准备数据:控制台读取System.in
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String data = reader.readLine();
            byte[] datas = data.getBytes();
            DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 6666));

            socket.send(packet);

            if (data.equals("bye")){
                break;
            }
        }

        socket.close();
    }
}
package com.wang.netStudy.chat;


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

public class UdpReceiveDemo01 {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(6666);

        while (true){
            //准备接收包裹
            byte[] container = new byte[1024];

            DatagramPacket packet = new DatagramPacket(container,0,container.length);

            socket.receive(packet);//阻塞式接收包裹

            //断开连接,bye
            byte[] data = packet.getData();
            String receiveData = new String(data, 0, data.length);

            System.out.println(receiveData);

            if (receiveData.equals("bye")){
                break;
            }
        }

        socket.close();
    }
}

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

上一篇:【转】mysql 大数据字段longblob 默认长度参数max_allowed_packet 过小导致导入失败


下一篇:Rtmp协议实现