我正在尝试使用Java构建服务器。 我的问题是:如果我同时有多个用户怎么办?答案是:多线程。但我不知道该怎么做。
例如,如果有两个客户端同时连接,并且服务器(谁做2 *号码):如果客户端1说" 50"对于服务器和客户端2" 10",服务器应返回" 100"到第一个客户和" 20"到了第二个。但我不确定我的代码是否有效。
服务器端:
#bacon:hover ~ div { // The selector will change the adjacent div on hover
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg");
}
#bacon2:hover ~ div {
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon2.JPG");
}
#bacon3:hover ~ div {
background: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon3.jpg");
}
客户方:
public class Server {
public static void main(String[] args){
ServerSocket socket;
try {
socket = new ServerSocket(4444);
Thread t = new Thread(new Accept(socket));
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
class Accept implements Runnable {
private ServerSocket socketserver;
private Socket socket;
private int nbrclient = 1;
public Accept(ServerSocket s){
socketserver = s;
}
public void run() {
try {
socket = socketserver.accept();
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message = in.readLine();
System.out.println(message);
out = new PrintWriter(socket.getOutputStream());
out.println("Pong");
out.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
如果您有任何想法(如何进行多线程以及如何验证我的代码是否有效,比如运行两个Clients.java并检查多线程是否有效)
答案 0 :(得分:1)
服务器端需要一个while循环:
public class Server {
public static void main(String[] args){
ServerSocket socket;
try {
while(true){
socket = new ServerSocket(4444);
Socket socketInstance = socket.accept();
Thread t = new Thread(new Accept(socketInstance));
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
class Accept implements Runnable {
private Socket socket;
private int nbrclient = 1;
public Accept(Socket s){
socket = s;
}
public void run() {
try {
in = new BufferedReader (new InputStreamReader (socket.getInputStream()));
String message = in.readLine();
System.out.println(message);//this message should be your number
Double number = Double.parseString(message);
out = new PrintWriter(socket.getOutputStream());
//out.println("Pong");
out.println(2*number +"");
out.flush();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端看起来不错。只需将out.println("Ping");
替换为out.println("50");
或您想要的任何内容。
首先启动服务器,然后启动多个客户端应用程序。如果您有任何错误,可以在此处发布,并查看具体情况。