MainServer.java
import java.net.*;
import java.io.*;
public class MainServer{
public static int PORT=1234;
public static void main(String args[]) {
ServerSocket serverSocket=null;
Socket socket=null;
try{
serverSocket=new ServerSocket(PORT);
}catch(Exception e){
System.out.println("Error is :"+e);
}
while(true){
socket=serverSocket.accept();
SubServer sub=new SubServer(socket);
sub.start();
}
serverSocket.close();
}
}
子服务器
import java.net.*;
import java.io.*;
public class SubServer extends Thread {
private Socket socket=null;
String receiveData;
public SubServer(Socket socket){
this.socket=socket;
}
public void run(){
DataInputStream dis=new DataInputStream(socket.getInputStream());
receiveData=dis.readLine();
System.out.println("client Message: "+receiveData);
}
}
错误是:
MainServer.java:27: error: unreachable statement
serverSocket.close();
^
MainServer.java:23: error: unreported exception IOException; must be caught or declared to be thrown
socket=serverSocket.accept();
^
MainServer.java:27: error: unreported exception IOException; must be caught or declared to be thrown
serverSocket.close();
^
Note: ./SubServer.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
3 errors
我看到了很多教程和引用资料,但我无法解决问题。单服务器和单个客户端运行正常,但多个客户端无法在单个服务器上进行通信。
我使用
Thread
类来处理多个客户端,但它给出了以上错误。我找不到我的错误在哪里。谢谢。
最佳答案
这里 :
while(true){
socket=serverSocket.accept();
SubServer sub=new SubServer(socket);
sub.start();
}
您编写了一个无限循环:
while(true){...}
。因此,while
语句之后的任何语句均不可访问。而编译错误:
serverSocket.close();
应该不是必需的,或者应该成为 Hook 关闭的一部分,例如:Runtime.getRuntime().addShutdownHook(new Thread(t-> serverSocket.close()));
另外两个编译错误:
请参阅未处理(捕获或抛出)的已检查异常
IOException
。由于
Thread.run()
没有声明任何异常,因此您必须捕获它:public void run(){
try {
DataInputStream dis = new DataInputStream(socket.getInputStream());
receiveData = dis.readLine();
System.out.println("client Message: " + receiveData);
} catch (IOException e) {
// handling of the exception : logging and probably end of execution of
the current thread
}
}
附带说明一下,调用
readLine()
对象的不推荐使用的DataInputStream
方法不是一个好主意。首选BufferedReader
: