JAVA 多线程实现聊天(UDP通信 )

/* * UDP实现相互传递消息 * */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; /* * 客服端/发送端 */ class Send implements Runnable{ private DatagramPacket dPacket; private DatagramSocket dSocket; public Send(DatagramSocket dSocket) { this.dSocket=dSocket; } @Override public void run() { // TODO Auto-generated method stub try { BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));//从键盘读取数据 String string; while ((string=bufferedReader.readLine())!=null) {//循环读取 if (string.equals("Bye")) { System.err.println("我下线了"); System.exit(0); } byte []buf=string.getBytes();//将输入的字符串转换为字节数组 /* * 获取本机IP(外网IP,我是发送到本机IP,也可以试试其它IP),然后从本机发送到18888的端口(在这里也就是发送到我自己的18888端口) */ String IP=InetAddress.getLocalHost().getHostAddress().toString(); dPacket=new DatagramPacket(buf, buf.length, InetAddress.getByName(IP), 18888); dSocket.send(dPacket); } } catch (Exception e) { // TODO: handle exception System.err.println("发送数据失败"); e.printStackTrace(); } } } /* *服务器/ 接受端 */ class Recive implements Runnable{ private DatagramPacket dPacket; private DatagramSocket dSocket; public Recive(DatagramSocket dSocket) { this.dSocket=dSocket; } @Override public void run() { // TODO Auto-generated method stub while (true) { byte[] buf=new byte[1024]; dPacket=new DatagramPacket(buf, buf.length); try { dSocket.receive(dPacket); String IP=dPacket.getAddress().getHostAddress(); String data=new String(dPacket.getData(), 0, dPacket.getLength()); int portString=dPacket.getPort(); System.out.println("IP:"+IP+"端口:"+portString+"\n"+data); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public class test { /** * @param args */ public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub new Thread(new Send(new DatagramSocket())).start(); new Thread(new Recive(new DatagramSocket(18888))).start(); } }

你可能感兴趣的:(JAVA 多线程实现聊天(UDP通信 ))