网络编程也有趣的,Java中有对系统网络IO操作的封装包:Socket。现在我们在本地电脑(网络)用它来模拟一个简单的群聊功能,以便能更好地对网络编程进行深刻的理解。
"Client"去连接"Host",可同时多有多个"Client"去连接"Host";
在IDEA中,要多开一个程序(重复运行一个程序),可能需要关闭配置的"single instance only",或者打开"Allow parallel run"。
即可实现应用多开(并行运行)。
这是一个服务主机端的模拟代码:
/**
* @ Annotation:模拟服务器,实现群聊(群发)
*/
public class Host {
public static void main(String[] args) {
try {
System.out.println("Host start");
List<Socket> onlineSocket = new ArrayList<>();
//assign port:8898
ServerSocket server = new ServerSocket(8898);
while (true) {
Socket socket = server.accept();//monitor port:8898
System.out.println("a client:" + socket.getRemoteSocketAddress() + " online");
new Thread(() -> {
System.out.println("current thread id of host for new client is:" + Thread.currentThread().getId());
try {
InputStream is = socket.getInputStream();
DataInputStream dis = new DataInputStream(is);
while (true) {
try {
String content = dis.readUTF(dis);
System.out.println(content);
//static content
for (Socket oc : onlineSocket) {
OutputStream os = oc.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(content);
dos.flush();
}
} catch (Exception e) {
System.out.println("a client:" + socket.getRemoteSocketAddress() + "offline");
onlineSocket.remove(socket);
dis.close();
socket.close();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
onlineSocket.add(socket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是一个客户端的模拟代码:
/**
* @ Author Jam·Li
* @ Date 2024/9/8 19:13
* @ version 1.0.0
* @ Annotation:模拟客户端,可多开
*/
public class Client {
public static void main(String[] args) {
try {
//Socket client = new Socket(InetAddress.getLocalHost(), 8898);
Socket client = new Socket("127.0.0.1", 8898);
new Thread(()->{
try {
InputStream is = client.getInputStream();
DataInputStream dis = new DataInputStream(is);
while (true){
try {
String msg = dis.readUTF(dis);
System.out.println(msg);
} catch (Exception e) {
dis.close();
client.close();
System.out.println("I offline: "+client.getRemoteSocketAddress()+" now.");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}).start();
OutputStream os = client.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
Scanner scanner = new Scanner(System.in);
while (true){
System.out.println("Input Content Please");
String msg = scanner.nextLine();
dos.writeUTF(msg);
dos.flush();
System.out.println("Sent.");
if (msg.equals("Bye")){
client.close();
dos.close();
System.out.println("See you~");
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
先打开服务主机端:
再打开客户端:
多开客户端:
如果此文对你有帮助,请一键三连,点赞收藏加关注!作者后续会更新更多高质量文章哦!谢谢!