我想创建能够与多个客户端连接的服务器。 我的主要职责是:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5556);
} catch (IOException ex) {
Logger.getLogger(MakaoServer.class.getName()).log(Level.SEVERE, null, ex);
}
while (true) {
try {
Socket connection = serverSocket.accept();
PlayerConnection playerConn = new PlayerConnection(connection);
playerConn.start();
} catch (IOException ex) {
System.out.println("Nie można było utworzyć gniazda.");
}
}
PlayerConnection是一个Thread类。运行方法:
public void run() {
InputStream input = null;
while (true) {
try {
input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String msg = reader.readLine();
System.out.println(msg);
} catch (IOException ex) {
Logger.getLogger(PlayerConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
}
当我运行客户端并向服务器发送消息时,它已收到但在下一个while循环迭代中连接.getInputStream();抛出一个Socket异常套接字已关闭。为什么呢?
java.net.SocketException: socket closed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:150)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:283)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:325)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:177)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:154)
at java.io.BufferedReader.readLine(BufferedReader.java:317)
at java.io.BufferedReader.readLine(BufferedReader.java:382)
at makaoserver.PlayerConnection.run(PlayerConnection.java:38)
答案 0 :(得分:6)
将输入流和缓冲读取器放在循环外。
可能创建连接到同一输入流的多个流导致此问题。
答案 1 :(得分:0)
试
public void run() {
InputStream input = null;
input = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
try {
String msg = reader.readLine();
System.out.println(msg);
} catch (IOException ex) {
Logger.getLogger(PlayerConnection.class.getName()).log(Level.SEVERE, null, ex);
} finally {
}
}
}
当你完成套接字时也不要忘记关闭套接字
try {
// Create objects
// do stuff
} finally {
if (obj != null) obj.close();
}