?
/* 使用UDP模式,编写一个聊天程序 有发送和接收数据2部分, 一个线程接收,一个线程发送 由于发送和接收动作是不一致的,所以要使用2个run方法 而且这两个方法要封装到不同的类中 本程序忽略了部分异常的处理,也未加入UI组件 这样比较简洁 发送端口9998 接受端口9999 用的是局域网广播地址,所以自己发的消息自己也收到了 [示例]:简易控制台聊天程序 */ import java.net.*; import java.io.*; class Demo { public static void main(String[] args) throws Exception { DatagramSocket sendSocket = new DatagramSocket(9998); //发送端 DatagramSocket receSocket = new DatagramSocket(9999); //接收端 new Thread(new MsgSend(sendSocket)).start(); //发送线程 new Thread(new MsgRece(receSocket)).start(); //接受线程 } } class MsgSend implements Runnable //发送 { private DatagramSocket dsock; public MsgSend(DatagramSocket dsock) { this.dsock= dsock; } public void run() { BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in)); String lineStr = null; try { while(true) { lineStr = bufr.readLine(); if(lineStr!=null) { if(lineStr.equals("over886")) { break; } else { byte[] dataBuf = lineStr.getBytes(); DatagramPacket dataPack = //数据打包 new DatagramPacket( dataBuf, dataBuf.length, InetAddress.getByName("192.168.1.255"), //广播 9999 //目标端口 ); dsock.send(dataPack); } } } bufr.close(); dsock.close(); } catch(Exception e) { throw new RuntimeException("发送失败!"); } } } class MsgRece implements Runnable //接收 { private DatagramSocket dsock; public MsgRece(DatagramSocket dsock) { this.dsock= dsock; } public void run() { try { while(true) { byte[] dataBuf = new byte[1024]; DatagramPacket dataPack = new DatagramPacket(dataBuf,dataBuf.length); dsock.receive(dataPack); //将获取的数据保存到指定的数据包 String ip = dataPack.getAddress().getHostAddress(); String data = new String(dataPack.getData(),0,dataPack.getLength()); int port = dataPack.getPort(); System.out.println(); System.out.println("来自ip为 "+ip+" <对方端口>: "+port+" 的消息"); System.out.println(data); } } catch(Exception e) { throw new RuntimeException("接受失败!"); } finally { dsock.close(); } } }
?
?
?