zoukankan      html  css  js  c++  java
  • Udp实现聊天

    /*
    编写一个聊天程序。
    有两部分,发送和接收,这两部分需要同时进行,就需要用到多线程技术。
    一个线程控制发送,一个控制接收。
    因为接收和发送时不同的动作,所以需要两个run方法,定义在两个类中。
    */
    import java.net.*;
    import java.io.*;
    import java.lang.Exception;
    class  Send implements Runnable
    {
    	private DatagramSocket ds;
    	public Send(DatagramSocket ds)
    	{
    		this.ds = ds;
    	}
    
    	public void run()
    	{
    		try
    		{
    			BufferedReader buffr = new BufferedReader(new InputStreamReader(System.in));
    			String line = null;
    			while((line = buffr.readLine()) != null)
    			{
    				if("886".equals(line))
    					break;
    				byte [] buff = line.getBytes();
    				DatagramPacket dp = new DatagramPacket(buff,0,buff.length,InetAddress.getByName("122.88.30.178"),10001);
    				ds.send(dp);
    			}
    			ds.close();
    		}
    		catch (Exception ex)
    		{
    			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 ex)
    		{
    			throw new RuntimeException("接收端失败。");
    		}
    
    	}
    }
    
    class ChatDemo
    {
    	public static void main(String [] args) throws Exception
    	{
    		DatagramSocket dsSend = new DatagramSocket();
    		DatagramSocket dsReceive = new DatagramSocket(10001);
    		new Thread(new Send(dsSend)).start();
    		new Thread(new Receive(dsReceive)).start();
    
    	}
    }

  • 相关阅读:
    Callable和Future 多线程
    【spring-boot】spring-boot 整合 ehcache 实现缓存机制
    java 设计模式http://www.runoob.com/design-pattern/design-pattern-tutorial.html
    DDD领域驱动设计(例子)
    js要怎么接收后端传的excel文件流?
    构建最小JDK Docker镜像 或者直接使用镜像:frolvlad/alpine-oraclejre8:slim
    JVM知识点总结
    DDD随笔-Axon
    HttpServletRequest  通用的post 请求
    List转数组
  • 原文地址:https://www.cnblogs.com/dengshiwei/p/4258423.html
Copyright © 2011-2022 走看看