1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > UDP Socket基本思路小程序(2) 多线程简单聊天程序

UDP Socket基本思路小程序(2) 多线程简单聊天程序

时间:2021-10-05 19:39:36

相关推荐

UDP Socket基本思路小程序(2) 多线程简单聊天程序

独角兽企业重金招聘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();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。