• 那些年的 网络通信之 UDP 数据报包传输---


    下面是 一个多线程,基于 UDP 用户数据报包 协议 的 控制台聊天小程序

    import java.io.*;
    import java.net.*;
    class Send implements Runnable{
    	  private  DatagramSocket ds;
    	  public   DatagramPacket dp;
    	  private  byte [] sendBuf;
    	  //private  final int port=10086; // Receive Port
    	  private  final String ipAddress="192.168.10.1";
    	  private  InputStream in=System.in;
    	  private  BufferedReader bufr;
    	  private  InputStreamReader inpstr;
    	  private  String line;
    	  
    	  public Send(DatagramSocket ds){
    		this.ds=ds;
    		}
    	 
    	  public void run(){
    		  try{
    			    bufr=new BufferedReader(new InputStreamReader(in));
    					while((line=bufr.readLine())!=null){
    						
    						sendBuf=line.getBytes();
    						dp=new DatagramPacket(sendBuf,sendBuf.length,InetAddress.getByName(ipAddress),Receive.port);
    						ds.send(dp);
    						if("end".equalsIgnoreCase(line)) break;
    					   
    					   }
    		  }
    		  catch(Exception e){
    			  e.printStackTrace();
    		  }
    		  finally{
    			  if(bufr!=null)
    			  try{
    				    bufr.close();
    					bufr=null;
    					}
    			  catch(IOException ioe){
    				  ioe.printStackTrace();
    			  }
    					
    		  }
    	  }
    		
    }
    class Receive implements Runnable{
    	private DatagramSocket ds;
    	public static final int port=10087;
    	public DatagramPacket dp;
    	private InetAddress inetAddress;
    	private byte[] receiveBuf=new byte[1024];
    	private String receiveMsg;
    	
    	public void run(){
    		try{
    			ds=new DatagramSocket(port);
    			while(true){
    						dp=new DatagramPacket(receiveBuf,0,receiveBuf.length);
    						ds.receive(dp);
    						inetAddress=dp.getAddress();
    						receiveBuf=dp.getData();
    						receiveMsg=new String(receiveBuf,0,dp.getLength());
    						if("end".equalsIgnoreCase(receiveMsg)) break;
    						System.out.println(inetAddress.getHostAddress()+":"+dp.getPort()+": "+receiveMsg);						
    			}
    		}
    		catch(Exception e){
    			e.printStackTrace();
    		}
    		
    	}
    }
    
    class ChatDemo{
    	 public static void main(String [] args) throws Exception{
    				new Thread(new Send(new DatagramSocket(10086))).start();  // send from 10086 port
    				new Thread(new Receive()).start();
    		}
    }

    Demo 示例图
    
    

      

    如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。
  • 相关阅读:
    mongo备份&恢复
    logstash参数配置
    elasticsearch索引自动清理
    Linux将公网ip映射到局域网ip
    普通用户创建ssh无密码访问
    软考介绍
    安装ffmpeg
    Hadoop实战-Flume之自定义Sink(十九)
    Hadoop实战-Flume之自定义Source(十八)
    Hadoop实战-Flume之Sink Load-balancing(十七)
  • 原文地址:https://www.cnblogs.com/Frank99/p/6669131.html
Copyright © 2020-2023  润新知