独角兽企业重金招聘Python工程师标准>>>
发送端
import java.io.BufferedReader;import java.io.InputStreamReader;import .DatagramPacket;import .DatagramSocket;import .InetAddress;/*** 发送端* @author Administrator**/public class Send implements Runnable{private DatagramSocket ds;public Send(DatagramSocket ds){this.ds = ds;}@Overridepublic void run() {try{BufferedReader br = new BufferedReader(new InputStreamReader(System.in));String line = null;while((line = br.readLine()) != null){byte[] b = line.getBytes();DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getByName("127.0.0.1"), 8888);//发送广播,群聊//DatagramPacket dp = new DatagramPacket(b, b.length, InetAddress.getByName("192.168.123.255"), 8888);ds.send(dp);if("over".equalsIgnoreCase(line))break;}ds.close();}catch(Exception e){e.printStackTrace();}}}
接收端
import .DatagramPacket;import .DatagramSocket;/*** 接收端* @author Administrator**/public class Receive implements Runnable {private DatagramSocket ds;public Receive(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {while (true) {byte[] b = new byte[1024];DatagramPacket dp = new DatagramPacket(b, b.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();int port = dp.getPort();String text = new String(dp.getData(), 0, dp.getLength());System.out.println(ip+":" + port + "==" + text);if("over".equalsIgnoreCase(text)){System.out.println("-----退出聊天-----");break;}}} catch (Exception e) {e.printStackTrace();}}}
测试
import java.io.IOException;import .DatagramSocket;/*** 测试* @author Administrator**/public class ChatTest {public static void main(String[] args) throws IOException {DatagramSocket dsend = new DatagramSocket();DatagramSocket dsRece= new DatagramSocket(8888);Send s = new Send(dsend);Receive r = new Receive(dsRece);new Thread(s).start();new Thread(r).start();}}