百人计划

写一个简易聊天程序

2017-06-18  本文已影响415人  寻叶亭

发送端代码如下:

  class Send implements  Runnable 
     {
        private DatagramSocket ds;//1.建立socket服务
        public Send(DatagramSocket ds) 
        {
            this.ds = ds;
        }
        public void run() 
        {
            try 
            {
                BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));//键盘输入
                String line = null;//line初始化为空
                while (null!=(line=bf.readLine()))//逐行读取
                {
                    byte [] bt = line.getBytes();//字节数据打包成数组
                    DatagramPacket dp = new DatagramPacket(bt, bt.length,InetAddress.getByName("192.168.1.255"),10086);
                    //2.打包后指定发送的ip和端口,255是一个广播地址,故是群发消息
                    ds.send(dp);//3.发送数据
                    if ("376".equals(line))//当输入消息为“376”时终止输入
                        break;//4.关闭资源
                }
            } 
            catch (Exception e) 
            {
                throw new RuntimeException("发送端失败");//抛异常
            }   
        }
    }

接收端代码

    class Rece implements  Runnable
     {
        private DatagramSocket ds;
        public Rece(DatagramSocket ds) 
        {
            this.ds = ds;
        }
        public void run() 
        {
            try 
            {
                while(true)
                {
                    byte [] buf = new byte[1024];//2.建立一个数据包用来存储接收的数据
                    DatagramPacket dp = new DatagramPacket(buf, buf.length);
                    ds.receive(dp);//接收数据
                    String ip =dp.getAddress().getHostAddress();
                    String data =new String(dp.getData(),0,dp.getLength());
                    if ("376".equals(data))//当某个发送端退出时
                        {
                            System.out.println(ip+"已退出聊天室");//打印提示
                            break;
                        }
                    System.out.println(ip+":"+data);//4.输出发送端的ip+数据包
                }       
            }
            catch (Exception e) 
            {
                throw new RuntimeException("接收端失败");
            }
        }
    }

主函数调用:

    class Chat 
    {
        public static void main(String[] args) throws Exception
        {
            DatagramSocket seSocket = new DatagramSocket();
            DatagramSocket reSocket = new DatagramSocket(10086);//接收端监听10086端口
            new Thread(new Send(seSocket)).start();
            new Thread(new Rece(reSocket)).start();
        }
    }

输出聊天结果:

  gc
  192.168.1.234:gc
  hello 寻叶亭
  192.168.1.234:hello 寻叶亭
  376
  192.168.1.234已退出聊天室
上一篇 下一篇

猜你喜欢

热点阅读