您好,登錄后才能下訂單哦!
本篇內容主要講解“Java中基于UDP多線程怎么實現在線咨詢的功能”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Java中基于UDP多線程怎么實現在線咨詢的功能”吧!
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 formPort; //自身端口
private String toIP; //發送到的IP
private int toPort; //發送到的端口
public TalkSend(int formPort, String toIP, int toPort) {
this.formPort = formPort;
this.toIP = toIP;
this.toPort = toPort;
try {
socket = new DatagramSocket(formPort);
reader = new BufferedReader(new InputStreamReader(System.in)); //獲取控制臺輸入
} catch (SocketException 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(packet.equals("bye")){
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
//接收線程
public class TalkReceive implements Runnable {
DatagramSocket socket = null; //與發送端的socket為同一個,實現通信
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);//接收數據
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();
}
}
//模擬學生
public class TalkStudent {
public static void main(String[] args) {
new Thread(new TalkSend(7777, "localhost", 9999)).start();
new Thread(new TalkReceive(8888, "老師")).start();
}
}
//模擬老師
public class TalkTeacher {
public static void main(String[] args) {
new Thread(new TalkSend(5555, "localhost", 8888)).start();
new Thread(new TalkReceive(9999, "學生")).start();
}
}
到此,相信大家對“Java中基于UDP多線程怎么實現在線咨詢的功能”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。