那些年的 网络通信之 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 示例图
![](https://images2015.cnblogs.com/blog/636379/201704/636379-20170406094000035-999731847.png)
如果有来生,一个人去远行,看不同的风景,感受生命的活力。。。