我写了一个服务器 - 客户端通信程序,它运行良好。
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);
}
}
}
以上是单个客户端的代码 - 服务器通信,现在我希望多个客户端与该服务器进行交互。我搜索了它,发现它可以通过使用一个线程为每个单个客户端与服务器通信来完成,但由于我是初学者,我不知道具体如何实现。所以有人请告诉我该怎么做或给我一些想法。
答案 0 :(得分:24)
MainServer类
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
}
答案 1 :(得分:3)
您想查看Java concurrency。这就是一个Java程序同时执行多个操作的概念。在较高级别,您将使用while(true) { //... }
块并将其作为实现Runnable的类的run()
方法的一部分运行。您将创建调用run()
方法的Thread实例,可能每个客户端都有一个。
要真正了解Java在并发方面提供的所有内容,请查看Java Concurrency in Practice。
答案 2 :(得分:1)
好吧,当我做类似的事情时,我实现了一个管理服务器端的监听器,所以当客户端(客户端可能不需要更改)连接时,服务器启动一个线程来处理该客户端。 / p>
while (!stop)
{
socket = serverSocket.accept();
HiloSocket hiloSocket = new HiloSocket(socket, this);
hiloSocket.start();
}
当然,HiloSocket扩展了Thread,它有管理客户端的逻辑......