我正在使用简单的套接字-套接字连接创建一个聊天室。我有一个服务器和客户端程序。服务器在端口 225 上运行,然后当我在端口 225 上运行客户端以便他们可以读取/写入套接字时,客户端立即停止并显示错误消息
java.net.SocketException: Connection resetJava Result: 1
为什么会抛出这个异常?它连接起来,该行打印到控制台,如图所示:
try {
client = new Socket(serverAdress, portNumber);
System.out.println("Successful connection to server on port " + portNumber + ".");
那么为什么它可能无法连接?
这是异常跟踪...
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
at java.io.InputStreamReader.read(InputStreamReader.java:167)
at java.io.BufferedReader.fill(BufferedReader.java:136)
at java.io.BufferedReader.readLine(BufferedReader.java:299)
at java.io.BufferedReader.readLine(BufferedReader.java:362)
at schoolroom10.SchoolRoomClient.SchoolRoomClientWindow.main(SchoolRoomClientWindow.java:85)
这是我的服务器代码...
public class SchoolRoomServer {
// 'server' will create the server over the local port:
static ServerSocket serverSocket = null;
//Socket for listening:
static Socket clientcommunicate = null;
//portnum is the number of the local port. Change to required port before running.
static int portnum = 225;
public static void main(String[] args) throws IOException{
try {
serverSocket = new ServerSocket(portnum);
clientcommunicate = serverSocket.accept();
Communicate c = new Communicate(Communicate.server);
Thread t = new Thread(c);
t.start();
} catch (UnknownHostException uhe) {
System.err.println(uhe);
System.exit(1);
} catch (IOException ioe) {
System.err.println(ioe);
System.exit(1);
}
}
}
class Communicate implements Runnable {
public static Socket server;
Communicate(Socket server) {
Communicate.server = server;
}
public void run() {
String in = "";
try {
//i/o for clients:
PrintStream output = new PrintStream(server.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(server.getInputStream()));
String message;
//Message handling:
while(((message = input.readLine()) != null) && (!in.equals("."))) {
output.println(message);
}
} catch (IOException ioe) {
System.err.println(ioe);
}
}
}