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 示例图
    
    

      

    如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。
  • 相关阅读:
    线性代数学习之初等矩阵和矩阵的可逆性
    线性代数学习之线性系统
    容器远程访问vnc--CentOS 6.8安装和配置VNC
    docker安装-单机/多机安装
    docker aufs存储驱动文件系统
    基于PowerCli自动部署和配置vmvare虚拟机
    使用Kubespray在ubuntu上自动部署K8s1.9.0集群
    python应用-pycharm新建模板默认添加shebang编码作者时间等信息
    python开发基础作业01:模拟登陆系统
    git 添加码云远程仓库和上传到码云的命令
  • 原文地址:https://www.cnblogs.com/Frank99/p/6669131.html
Copyright © 2011-2022 走看看