gpt4 book ai didi

java - Java中的多个客户端到服务器通信程序

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:24 25 4
gpt4 key购买 nike

我写了一个服务器-客户端通信程序,运行良好。

客户端模块

import java.io.*;
import java.net.*;

class Client {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
while(true){
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("myname.domain.com", 2343);

DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

System.out.println("Ready");
sentence = in.readLine();
out.writeBytes(sentence + '\n');
modifiedSentence = in.readLine();
System.out.println(modifiedSentence);
}
clientSocket.close();
}
}

服务器模块

import java.net.*;

public class Server {
public static void main(String args[]) throws Exception {
String clientSentence;
String cap_Sentence;
ServerSocket my_Socket = new ServerSocket(2343);

while(true) {
Socket connectionSocket = my_Socket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream out = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = in.readLine();
cap_Sentence = "Raceived:" + clientSentence + '\n';
out.writeBytes(cap_Sentence);
}
}
}

上面是单个客户端-服务器通信的代码,现在我要多个客户端与那个服务器交互。我在谷歌上搜索了一下,发现它可以通过为每个客户端使用一个线程来与服务器通信来完成,但是由于我是初学者,所以我不知 Prop 体如何实现。所以有人请告诉我该怎么做或给我一些想法。

最佳答案

主服务器类

public class Server {

public static void main(String[] args) throws IOException {

ServerSocket serverSocket = null;

boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(2343);
} catch (IOException e) {
System.err.println("Could not listen on port: 2343");
}

while(listeningSocket){
Socket clientSocket = serverSocket.accept();
MiniServer mini = new MiniServer(clientSocket);
mini.start();
}
serverSocket.close();
}

}

助手类

public class MiniServer extends Thread{

private Socket socket = null;

public MiniServer(Socket socket) {

super("MiniServer");
this.socket = socket;

}

public void run(){
//Read input and process here
}
//implement your methods here

}

关于java - Java中的多个客户端到服务器通信程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5419328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com