初始化聊天房间信息… 确定当前 用户的端口号和目标端口号 并据此 创建两个线程-- 接收端线程 发送端线程!
package network.udpchat;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;
public class ChatRoom {
public static void main(String[] args) {
System.out.println("欢迎进入聊天系统!!!");
Scanner scanner = new Scanner(System.in);
System.out.println("请输入当前聊天服务端口号:");
int thisPort = scanner.nextInt();
System.out.println("请输入目标服务端口号:");
int targetPort = scanner.nextInt();
System.out.println("系统初始化已完成!");
try {
DatagramSocket socket = new DatagramSocket(thisPort);
new Thread(new ChatSend(socket,targetPort),"发送端线程").start();
new Thread(new ChatReceiver(socket),"接收端线程").start();
} catch (SocketException e) {
e.printStackTrace();
}
}
}
定义接收端信息的线程
package network.udpchat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.Arrays;
public class ChatReceiver implements Runnable{
private DatagramSocket datagramSocket;
public ChatReceiver(DatagramSocket datagramSocket){
this.datagramSocket=datagramSocket;
}
@Override
public void run() {
byte[] bytes=new byte[1024];
DatagramPacket packet = new DatagramPacket(bytes, bytes.length);
while (true){
try {
datagramSocket.receive(packet);
String name=packet.getPort() == 3000?"杨哥":"马硕森";
String tx =new String(packet.getData(),0,packet.getLength());
System.out.println("收到来自"+name+"发来的消息:"+tx);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
定义发送端线程
package network.udpchat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class ChatSend implements Runnable{
private DatagramSocket sender;
private int targetPort;
public ChatSend(DatagramSocket datagramSocket,int targetPort){
this.sender=datagramSocket;
this.targetPort=targetPort;
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
String name = targetPort==9000?"杨哥":"马硕森";
try {
while (true) {
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("我:"+"("+name+")"+":\n");
String text = scanner.nextLine();
byte[] bytes = text.getBytes();
DatagramPacket packet = new DatagramPacket(bytes, bytes.length, localHost, targetPort);
sender.send(packet);
System.out.println("************系统提示:发送信息成功! ***********************");
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
效果:
|