UDP协议的控制台聊天

UDP的特点是速度快,不安全

UDP的控制台聊天实现的原理是一个发送端,一个接收端,发送端负责发送数据打包,接收端负责拆包,解析,我们用循环分别让发送端和接收端一直运行,并且通过线程让他们异步运行,这样,只要两台电脑上都有这个程序,并设置好端口号和IP,就可以实现控制台聊天了。

代码如下:

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class Talk {
     // UDP????
     public static void main( String[] args) throws SocketException, Exception {
         // ??????????????
         new Thread( new Runnable() {

             @Override
             public void run() {
                 while ( true) {
                     try {
                         //本机的端口号设置为8888
                         DatagramSocket ds = new DatagramSocket( 8888);
                         byte[] buf = new byte[ 1024];
                         int length = buf. length;
                         DatagramPacket dp = new DatagramPacket(buf, length);
                         ds. receive(dp);
                         // 拆包
                         InetAddress ip = dp. getAddress();
                         byte[] data = dp. getData();
                         int length1 = dp. getLength();
                         // 设置打印在控制台的格式
                         String s1 = new String(data, 0, length1);
                         SimpleDateFormat sdf = new SimpleDateFormat( "HH:mm:ss");
                         String time = sdf. format( new Date());
                         String message = dp. getAddress(). getHostAddress()+time+ " "+s1;
                         System. out. println(message);
                         ds. close();
                    } catch ( SocketException e) {
                         e. printStackTrace();
                    } catch ( IOException e) {
                         e. printStackTrace();
                    }
                }
            }
        }). start();

         while ( true) {
             //接收端
             DatagramSocket ds = new DatagramSocket();
             // 键盘录入
             Scanner sc = new Scanner( System. in);
             String s = sc. nextLine();
             SimpleDateFormat sdf = new SimpleDateFormat( "HH:mm:ss");
             String time = sdf. format( new Date());
             String message = time+ " "+s;
             byte[] bytes = message. getBytes();
             int len = bytes. length;
             // 设置对面的端口号和IP,联机的时候需要根据对方电脑设置
             InetAddress ia = InetAddress. getByName( "127.0.0.1");
             int port = 8888;
             // 打包并发送
             DatagramPacket packet = new DatagramPacket(bytes, len, ia, port);
             ds. send(packet);

        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值