使用UDP實現簡單多人聊天功能
阿新 • • 發佈:2019-02-02
使用UDP實現簡單聊天功能
使用UDP實現一個簡單的多人聊天功能。該程式使用了多執行緒,實現了聊天功能。
package 課後作業.E103_10_聊天;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
//接收
class Receive implements Runnable{
@Override
public void run() {
DatagramSocket receiveSocket = null;
try {
receiveSocket = new DatagramSocket(5200);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
byte[] bytes = new byte[1024];
//建立一個報文,於與接收
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
//接收
try {
receiveSocket.receive(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
InetAddress ip = datagramPacket.getAddress();
System.out.println(ip.getHostName()+ new String(datagramPacket.getData()));
}
}
}
//傳送
class Send implements Runnable{
@Override
public void run() {
DatagramSocket sendSocket = null;
try {
sendSocket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
Scanner scan = new Scanner(System.in);
while (true) {
String str = scan.next();
//要傳送的資訊
byte[] bytes = str.getBytes();
//傳送的目標地址
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByName("192.168.108.32");
} catch (UnknownHostException e) {
e.printStackTrace();
}
//資料報文
DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length, inetAddress, 5200);
//傳送
try {
sendSocket.send(datagramPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class Test {
public static void main(String[] args) {
Receive receive = new Receive();
Thread thread = new Thread(receive);
thread.start();
Send send = new Send();
Thread thread1 = new Thread(send);
thread1.start();
}
}
執行結果:
這裡實現的是兩人聊天,想要實現多人聊天只需要將接受地址改成廣播地址即可。