UDP多线程在线咨询

Posted 逆骨111

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UDP多线程在线咨询相关的知识,希望对你有一定的参考价值。

package kuangs.chat;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable{
DatagramSocket socket = null;
private int port;
private String msgFrom;

public TalkReceive(int port, String msgFrom) {
this.port = port;
this.msgFrom = msgFrom;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
e.printStackTrace();
}
}

@Override
public void run() {
while (true){

try {
//准备接收包裹
byte[] container = new byte[1024];
DatagramPacket packet = new DatagramPacket(container,0,container.length);
socket.receive(packet);//阻塞式接收包裹
//断开连接 bye
byte[] data = packet.getData();
String receiveData = new String(data, 0, data.length);

System.out.println(msgFrom+":"+receiveData);

if(receiveData.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}



package kuangs.chat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

public class TalkSend implements Runnable {
DatagramSocket socket = null;
BufferedReader reader = null;

private int fromPort;
private String toIP;
private int toPort;

public TalkSend(int fromPort, String toIP, int toPort) {
this.fromPort = fromPort;
this.toIP = toIP;
this.toPort = toPort;

try {
socket = new DatagramSocket(fromPort);
//准备数据:控制台读取 System.in
reader = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void run() {

while (true){

try {
String data = reader.readLine();
byte[] datas = data.getBytes();

DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));

socket.send(packet);
if (data.equals("bye")){
break;
}
} catch (Exception e) {
e.printStackTrace();
}

}
socket.close();
}
}



package kuangs.chat;

public class TalkTeacher {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(5555,"localhost",8888)).start();
new Thread(new TalkReceive(9999,"学生")).start();
}
}



package kuangs.chat;

public class TalkStudent {
public static void main(String[] args) {
//开启两个线程
new Thread(new TalkSend(7777,"localhost",9999)).start();
new Thread(new TalkReceive(8888,"老师")).start();
}
}

以上是关于UDP多线程在线咨询的主要内容,如果未能解决你的问题,请参考以下文章

多线程实现udp网络通信

多任务-python实现-UDP多线程聊天(2.1.6)

Java学习网络编程全总结——TCPUdp多线程IO流Socket简易在线咨询聊天室Java爬虫

多线程 Thread 线程同步 synchronized

案例:多任务版udp聊天器

网络编程——Java