zoukankan      html  css  js  c++  java
  • 那些年的 网络通信之 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 示例图
    
    

      

    如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。
  • 相关阅读:
    windows中dos命令指南
    HDU 2084 数塔 (dp)
    HDU 1176 免费馅饼 (dp)
    HDU 1004 Let the Balloon Rise (map)
    变态杀人狂 (数学)
    HDU 2717 Catch That Cow (深搜)
    HDU 1234 开门人和关门人 (模拟)
    HDU 1070 Milk (模拟)
    HDU 1175 连连看 (深搜+剪枝)
    HDU 1159 Common Subsequence (dp)
  • 原文地址:https://www.cnblogs.com/Frank99/p/6669131.html
Copyright © 2011-2022 走看看