zoukankan      html  css  js  c++  java
  • 通过socket和Udp协议简单实现一个群体聊天工具(控制台)

    编写一个聊天程序。
    有收数据的部分 和 发数据的部分。
    这两个部分需要同时执行,
    这就用到多线程技术,
    一个线程负责收,一个现象负责发。

    因为收和发动作是不一致的,所以要定义两个run方法
    而且这两个方法要封装到不同类中。

    import java.net.*;
    import java.io.*;
    

    发送端:

    class Send implements Runnable
    {
    	private DatagramSocket ds;
    	public Send(DatagramSocket ds)
    	{
    		this.ds=ds;
    	}
    	public void run()
    	{
    		try
    		{
    			BufferedReader bufr=
    				new BufferedReader(new InputStreamReader(System.in));
    			String line=null;
    
    			while((line=bufr.readLine())!=null)
    			{
    				if ("886".equals(line))
    					break;
    
    				byte[] buf=line.getBytes();
    
    				DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.1.102"),10002);
    				//DatagramPacket dp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.1"),10002);
    				
    				ds.send(dp);
    			}
    		
    		}
    		catch (Exception e)
    		{
    			throw new RuntimeException("发送失败");
    		}
    	}
    }
    

    接收端:

    class Receive implements Runnable
    {
    	private DatagramSocket ds;
    	public Receive(DatagramSocket ds)
    	{
    		this.ds=ds;
    	}
    	public void run()
    	{
    		try
    		{
    			//循环接收
    			while (true)
    			{
    				byte[] buf=new byte[1024];
    
    				DatagramPacket dp=new DatagramPacket(buf,buf.length);
    				
    				ds.receive(dp);
    				
    				String ip=dp.getAddress().getHostAddress();
    				
    				String data=new String (dp.getData(),0,dp.getLength());
    
    				System.out.println(ip+":"+data);
    
    			}
    		}
    		catch (Exception e)
    		{
    			throw new RuntimeException("接收失败");
    		}
    	}
    
    }
    

    主函数:

    class ChatDemo
    {
    	public static void main(String[] args) throws Exception
    	{
    		DatagramSocket sendSocket=new DatagramSocket();
    		DatagramSocket receiveSocket=new DatagramSocket(10002);
    
    		new Thread(new Send(sendSocket)).start();
    		new Thread(new Receive(receiveSocket)).start();
    	}
    }
    

      

  • 相关阅读:
    caffe用到的命令和零碎知识
    Manjaro — ssh出现22端口拒绝访问问题(port 22: Connection refused)
    Linux 解压z01 .z02 .z03... zip分卷
    Manjaro_Windows双系统安装
    Linux 的chsh命令
    mat2json, python读取mat成字典, 保存json
    最便捷的caffe编译方法 ---- cmake+anaconda虚拟环境
    复制跳过软链接
    使用Screen解决ssh连接中断导致的训练中断问题
    Caffe训练时Loss=87.3365问题
  • 原文地址:https://www.cnblogs.com/xiangyangzhu/p/ChatUdp.html
Copyright © 2011-2022 走看看