UDP实现相互聊天
本文使用 java语言编写了一个简单的通信程序,使用了多线程和udp的通信方式。
发送端
实现步骤
- 实现Runnable保证可以相互发送
- 建立socket连接
- 建立发送数据包
- 获取发送目标ip 和端口
- 从控制台获取需发送的信息
- 对信息进行格式转换
- 发送数据包
- 释放资源
实现代码
public class Send implements Runnable {
DatagramSocket socket = null;
DatagramPacket packet = null;
Scanner in = null;
private int fromProt;
private String toIP;
private int toProt;
public Send(int fromProt, String toIP, int toProt) {
this.fromProt = fromProt;
this.toIP = toIP;
this.toProt = toProt;
try {
socket = new DatagramSocket(fromProt);
in = new Scanner(System.in);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
try{
String sendMsg = in.nextLine();
byte[] buffer = sendMsg.getBytes();
packet = new DatagramPacket(buffer,0,buffer.length,new InetSocketAddress(this.toIP,this.toProt));
socket.send(packet);
if(sendMsg.equals("end")) break;
}catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
接收端
实现步骤
- 实现Runnable保证可以相互发送
- 开放端口
- 接受发送端的数据包
- 获取聊天数据
- 在控制台输出
- 释放资源
实现代码
public class Receive implements Runnable {
DatagramSocket socket = null;
DatagramPacket packet = null;
private int port;
public Receive(int port) {
this.port = port;
try {
socket = new DatagramSocket(this.port);
}catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
try {
byte[] buffer = new byte[1024];
packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveMsg = new String(data,0, data.length);
System.out.println(receiveMsg);
if(receiveMsg.equals("end")) break;
}catch (Exception e) {
e.printStackTrace();
}
}
socket.close();
}
}
主函数
用户A
public class ChatA {
public static void main(String[] args) {
new Thread(new Send(3001,"localhost",4399)).start();
new Thread(new Receive(8888)).start();
}
}
用户B
public class ChatB {
public static void main(String[] args) {
new Thread(new Send(2001,"localhost",8888)).start();
new Thread(new Receive(4399)).start();
}
}
|