11月25, 2020

Socket编程UDP实现聊天

通过Socket网络编程,UDP实现简单聊天。主要涉及DatagramSocket进行数据传输、DatagramPacket进行数据包封装,2个类。

发送端:

package learn.javase.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

/**
 * 控制台输入;实现聊天。
 * 发送方
 * @author Jole
 *
 */
public class UdpSend {

    public static void main(String[] args) throws Exception{
        Scanner scan = new Scanner(System.in);
        InetAddress ia = InetAddress.getByName("192.168.1.4");
        DatagramSocket socket = new DatagramSocket();
        while(true) {
            String chatInfo = scan.nextLine();
            byte[] info = chatInfo.getBytes();
            DatagramPacket pack = new DatagramPacket(info, info.length, ia, 6000);

            socket.send(pack);
        }
    }

}

接收端:

package learn.javase.chat;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
 * UDP:接收方
 * @author Jole
 *
 */
public class UdpReceive {

    public static void main(String[] args) throws Exception{
        DatagramSocket socket = new DatagramSocket(6000);
        byte[] info = new byte[1024];
        while(true) {
            DatagramPacket pack = new DatagramPacket(info, info.length);
            socket.receive(pack);
            InetAddress ia = pack.getAddress();
            System.out.println(ia.getHostName()+"-"+pack.getPort()+":"+new String(info,0,pack.getLength()));
        }

    }

}

本文链接:https://www.yanxizhu.com/post/udp.html

-- EOF --

Comments