【案例9-1】模拟微信聊天
如今微信已经成为人们生活中必不可少的一款社交软件。本案例要求编写一个程序模拟微信聊天功能。在实现案例时,要求使用多线程与 UDP 通信完成消息的发送和接收。
实现思路:创建两个用户,每个用户既是发送端又是接收端,利用多线程根据不同端口发送。
【实现代码】
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
/**
* ZAY 2023.7.31
*/
public class Example19{
public static void main(String[] args) throws IOException {
new User1re().start();
new User1se().start();
}
}
class User1re extends Thread{
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(6666);
} catch (SocketException e) {
throw new RuntimeException(e);
}
DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
while(true) {
try {
ds.receive(dp);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] arr = dp.getData();
int len = dp.getLength();
System.out.println("接受信息来自小明:" + new String(arr,0,len));
}
}
}
class User1se extends Thread {
@Override
public void run() {
DatagramSocket ds;
try {
ds = new DatagramSocket();
} catch (SocketException e) {
throw new RuntimeException(e);
}
Scanner sc = new Scanner(System.in);
while (true) {
String str = sc.nextLine();
System.out.println("小红发送信息");
if ("exit".equals(sc))
break;
DatagramPacket dp;
try {
dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
InetAddress.getByName("winner"), 7777);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
try {
ds.send(dp);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
ds.close();
}
}
/**
* ZAY 2023.7.31
*/
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Example20 {
public static void main(String[] args) {
new User2re().start();
new User2se().start();
}
}
class User2se extends Thread {
@Override
public void run() {
DatagramSocket ds;
try {
ds = new DatagramSocket();
} catch (SocketException e) {
throw new RuntimeException(e);
}
Scanner sc = new Scanner(System.in);
while (true) {
String str = sc.nextLine();
System.out.println("小明发送信息");
if ("exit".equals(sc))
break;
DatagramPacket dp;
try {
dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
InetAddress.getByName("winner"), 6666);
} catch (UnknownHostException e) {
throw new RuntimeException(e);
}
try {
ds.send(dp);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
ds.close();
}
}
class User2re extends Thread{
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(7777);
} catch (SocketException e) {
throw new RuntimeException(e);
}
DatagramPacket dp = new DatagramPacket(new byte[1024],1024);
while(true) {
try {
ds.receive(dp);
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] arr = dp.getData();
int len = dp.getLength();
System.out.println("接受信息来自小红:" + new String(arr,0,len));
}
}
}
【运行截图】