基于UDP的socket聊天室

来源:互联网 发布:域名ip查询 编辑:程序博客网 时间:2024/06/11 02:05

今天学习了一下利用UDP传输协议进行的socket通讯。

先上代码:

class Send implements Runnable {private DatagramSocket ds;Send(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));String line = null;while ((line = bufr.readLine()) != null) {if ("886".equals(line)) {break;}byte[] buf = line.getBytes();DatagramPacket dp = new DatagramPacket(buf, buf.length,InetAddress.getByName("211.64.154.152"), 10002);ds.send(dp);}} catch (Exception e) {throw new RuntimeException("发送端失败");}}}class Rece implements Runnable {private DatagramSocket ds;Rece(DatagramSocket ds) {this.ds = ds;}@Overridepublic void run() {try {while (true) {byte[] buf = new byte[1024];DatagramPacket dp = new DatagramPacket(buf, buf.length);ds.receive(dp);String ip = dp.getAddress().getHostAddress();String data = new String(dp.getData(), 0, dp.getLength());System.out.println(ip + "::" + data);}} catch (Exception e) {throw new RuntimeException("接收失败");}}}class ChatDemo {public static void main(String[] args) {try {DatagramSocket sendSocket = new DatagramSocket();DatagramSocket receSocket = new DatagramSocket(10002);new Thread(new Send(sendSocket)).start();new Thread(new Rece(receSocket)).start();} catch (Exception e) {e.printStackTrace();}}}

在主函数中,利用DatagramSocket,写出两个线程,一个用于发送,一个用于接收。

 

0 0
原创粉丝点击