标签:class esc ddr auth port com stack res from
package com.yjf.esupplier.common.test; import java.net.DatagramSocket; import java.net.SocketException; /** * @author shusheng * @description 通过多线程改进,在一个窗口中同时接收又发送 * @Email shusheng@yiji.com * @date 2019/1/10 23:12 */ public class ChatRoom { public static void main(String[] args) throws SocketException { DatagramSocket dsSend = new DatagramSocket(); DatagramSocket dsReceive = new DatagramSocket(12306); SendThread st = new SendThread(dsSend); ReceiveThread rt = new ReceiveThread(dsReceive); Thread t1 = new Thread(st); Thread t2 = new Thread(rt); t1.start(); t2.start(); } }
package com.yjf.esupplier.common.test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.Scanner; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2019/1/10 23:16 */ public class SendThread implements Runnable { private DatagramSocket socket; public SendThread(DatagramSocket socket) { this.socket = socket; } @Override public void run() { try { String line = null; while (true) { Scanner scan = new Scanner(System.in); line = scan.nextLine(); if (line.equals("exit")) { break; } byte[] bytes = line.getBytes(); DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("localhost"), 12306); socket.send(packet); } socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
package com.yjf.esupplier.common.test; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; /** * @author shusheng * @description * @Email shusheng@yiji.com * @date 2019/1/10 23:27 */ public class ReceiveThread implements Runnable { private DatagramSocket socket; public ReceiveThread(DatagramSocket socket) { this.socket = socket; } @Override public void run() { try { while (true) { // 创建一个包裹 byte[] bys = new byte[1024]; DatagramPacket dp = new DatagramPacket(bys, bys.length); // 接收数据 socket.receive(dp); // 解析数据 String ip = dp.getAddress().getHostAddress(); String s = new String(dp.getData(), 0, dp.getLength()); System.out.println("from " + ip + " data is : " + s); } } catch (IOException e) { e.printStackTrace(); } } }
标签:class esc ddr auth port com stack res from
原文地址:https://www.cnblogs.com/zuixinxian/p/11275396.html