UDP通过多线程改进,在一个窗口中同时接收又发送
Posted zuixinxian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP通过多线程改进,在一个窗口中同时接收又发送相关的知识,希望对你有一定的参考价值。
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();
以上是关于UDP通过多线程改进,在一个窗口中同时接收又发送的主要内容,如果未能解决你的问题,请参考以下文章
TCP socket 多线程 并发服务器(发送)与客户端(接收)