java网络编程案例9-1模拟微信聊天
Java网络编程案例9-1模拟微信聊天
概述
本案例要求编写一个程序模拟微信聊天功能。在实现本案例时,要求使用多线程与UDP通信完成消息的发送和接收。
需求分析
在微信聊天中,我们需要实现以下功能:
1. 用户登录:用户输入用户名和密码后,服务器端验证用户名和密码是否正确,如果正确,则返回登录成功信息。
2. 消息发送:用户可以向其他用户发送消息,消息内容包括文本、图片、视频等类型。
3. 消息接收:当其他用户收到消息时,会显示在聊天界面中。
实现方案
为了实现上述功能,我们需要使用多线程和UDP通信。具体来说:
1. 使用多线程来处理发送和接收消息的任务。
2. 使用UDP通信来传输消息。
代码实现
SendTask类
```javapackage GGS3;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class SendTask implements Runnable {
private String msg;
private InetAddress serverIP;
private int port;
public SendTask(String msg, InetAddress serverIP, int port) {
this.msg = msg;
this.serverIP = serverIP;
this.port = port;
}
@Override public void run() {
try {
byte[] data = msg.getBytes();
DatagramPacket packet = new DatagramPacket(data, data.length, serverIP, port);
java.net.DatagramSocket socket = new java.net.DatagramSocket();
socket.send(packet);
System.out.println("消息发送成功!");
socket.close();
} catch (Exception e) {
System.out.println("消息发送失败!");
}
}
}
```
ReceiveTask类
```javapackage GGS3;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class ReceiveTask implements Runnable {
private InetAddress serverIP;
private int port;
public ReceiveTask(InetAddress serverIP, int port) {
this.serverIP = serverIP;
this.port = port;
}
@Override public void run() {
try {
java.net.DatagramSocket socket = new java.net.DatagramSocket(port);
byte[] data = new byte[1024];
DatagramPacket packet = new DatagramPacket(data,0, serverIP, port);
socket.receive(packet);
String msg = new String(data,0, packet.getLength());
System.out.println("收到消息:" + msg);
socket.close();
} catch (Exception e) {
System.out.println("消息接收失败!");
}
}
}
```
Main类
```javapackage GGS3;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class Main {
public static void main(String[] args) throws UnknownHostException {
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port =12345;
SendTask sendTask = new SendTask("Hello, world!", serverIP, port);
ReceiveTask receiveTask = new ReceiveTask(serverIP, port);
Thread threadSend = new Thread(sendTask);
Thread threadReceive = new Thread(receiveTask);
threadSend.start();
threadReceive.start();
}
}
```
总结
本案例实现了一个简单的微信聊天功能,使用多线程和UDP通信完成消息的发送和接收。用户可以向其他用户发送消息,并实时接收到对方发来的消息。