• socket进行简单聊天


    简单聊天:UDP实现

    发送端代码

    package com.wangjie.chat;
    
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetSocketAddress;
    import java.net.SocketException;
    
    public class UdpSenderDemo01 {
        public static void main(String[] args) throws Exception {
    
            DatagramSocket socket = new DatagramSocket(9999);
    
            // 准备数据,控制台读取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.wangjie.chat;
    
    public class TalkStudent {
    
        public static void main(String[] args) {
            // 开启两个线程
            new Thread(new TalkSend(7777,"localhost",9899)).start();
            new Thread(new TalkReceive(8890,"老师")).start();
    
    
        }
    }
    

    接收端代码:

    package com.wangjie.chat;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.SocketException;
    
    public class UdpReceiveDemo01 {
        public static void main(String[] args) throws Exception {
    
            DatagramSocket socket = new DatagramSocket(6666);
    
    
            while (true) {
                // 准备接收包裹
                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(receiveData);
    
                if (receiveData.equals("bye")) {
                    break;
                }
            }
            socket.close();
        }
    }
    
    

    接收端调用代码:

    package com.wangjie.chat;
    
    public class TalkTeacher {
    
        public static void main(String[] args) {
            new Thread(new TalkSend(5555,"localhost",8890)).start();
            new Thread(new TalkReceive(9899,"学生")).start();
        }
    }
    
    
  • 相关阅读:
    Linux下中文乱码
    hive配置元数据库mysql文件配置
    centos7安装mysql5.6
    mapreduce案例:获取PI的值
    hadoop第一个程序WordCount
    centos7搭建伪分布式集群
    Centos7永久关闭防火墙
    centos7设置静态ip
    大数据技术之kettle
    2020/6/20 mysql表连接和子查询
  • 原文地址:https://www.cnblogs.com/spider3658/p/15891786.html
Copyright © 2020-2023  润新知