gpt4 book ai didi

java - Java-服务器可同时为多个客户端提供服务

转载 作者:行者123 更新时间:2023-12-03 11:55:06 25 4
gpt4 key购买 nike

我编写了一个程序,该程序实现了简单的服务器-客户端连接和通信,但仅适用于一个客户端。如果我启动第二个客户端,它什么也不会做,只会给出“Out:0”作为输出。 (服务器未响应)

我在服务器中使用线程,但我不知道为什么此解决方案无法正常工作。

任何的想法?

(我知道空的捕获并不好,但这只是示例代码。)

Server.java:

public class Server implements Runnable {
final int port;

public Server(int port){
this.port=port;
}

@Override
public void run(){
while(true){
try{
ServerSocket ss = new ServerSocket(port);
new ClientThread(ss).start();
}catch(Exception e){}
}
}

public static void main(String[] args){
new Server(1995).run();
}

private class ClientThread extends Thread{
Socket s;
Scanner sc;
PrintWriter pw;

ClientThread(ServerSocket ss){
try{
this.s = ss.accept();
}catch(Exception e){}
}

@Override
public void start(){
try{
String in,out;

sc = new Scanner(s.getInputStream());
pw = new PrintWriter(s.getOutputStream(), true);
int i=0;
do{
in = sc.nextLine();
System.out.println("In: " + in);
int tmp = Integer.parseInt(in)+1;
out = Integer.toString(tmp);
pw.println(out);
i++;
}while(i<10);
}catch(Exception e){}
}
}
}

Client.java:
public class Client implements Runnable{
String host;
int port;
Socket s;
Scanner sc;
PrintWriter pw;

public Client(String host, int port){
this.host=host;
this.port=port;
}

@Override
public void run(){
try{
s = new Socket(host, port);

sc = new Scanner(s.getInputStream());
pw = new PrintWriter(s.getOutputStream(), true);

String in, out;
out="0";
int i=0;
do{
pw.println(out);
System.out.println("Out: " + out);
in = sc.nextLine();
int tmp = Integer.parseInt(in)+1;
out=Integer.toString(tmp);
}while(i<10);

}catch(Exception e){}
}

public static void main(String[] args){
new Client("localhost", 1995).run();
}
}

最佳答案

您不必覆盖start(),而必须覆盖run()

private class ClientThread extends Thread{
Socket s;
Scanner sc;
PrintWriter pw;

ClientThread(Socket s){
this.s = s;
}

@Override
public void run() {
try{
String in,out;

sc = new Scanner(s.getInputStream());
pw = new PrintWriter(s.getOutputStream(), true);
int i=0;
do{
in = sc.nextLine();
System.out.println("In: " + in);
int tmp = Integer.parseInt(in)+1;
out = Integer.toString(tmp);
pw.println(out);
i++;
}while(i<10);
}catch(Exception e){}
}
}

服务器线程:
@Override
public void run(){
try{
ServerSocket ss = new ServerSocket(port);
while(true){
Socket cl = ss.accept();
new ClientThread(cl).start();
}
}catch(Exception e){}
}

关于java - Java-服务器可同时为多个客户端提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544760/

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