可能重复期间发送一些数据:
Java socket sends some data during connection to server的Java套接字连接到服务器2
我有两个非常非常简单的Java程序 - 客户端和server.They建立通过socket连接。 服务器从流中读取字符并将其打印到控制台。
import java.net.*;
import java.io.*;
import java.util.Date;
public class DataServerSIMS {
static final int LISTENING_PORT = 2002;
public static void main(String[] args) {
ServerSocket listener; //Checks the connection requests
Socket connection; //To interact with other progs
Reader incoming; //Stream
try {
listener = new ServerSocket(LISTENING_PORT);
TextIO.putln("Listening on port "+LISTENING_PORT);
while (true) {
connection = listener.accept();
try {
incoming = new InputStreamReader(connection.getInputStream());
while (true) {
int ch = incoming.read();
if (ch == 1 || ch == '\r')
break;
System.out.print((char)ch);
}
System.out.println();
incoming.close();
}
catch (IOException e) {
TextIO.putln("Error: "+e);
}//end try recieving data
}//end while
}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: "+e);
return;
}
}
}
客户端只建立套接字连接。
import java.net.*;
import java.io.*;
import java.util.Date;
public class TempClientSIMS {
//static final int LISTENING_PORT = 32007;
static final int LISTENING_PORT = 2002;
public static void main(String[] args) {
ServerSocket listener; //Checsk the connection requests
Socket connection; //To interact with other progs
Socket connectionToServer = null; //Socket
Reader incoming; //Stream
try {
TextIO.putln("Localhost connects to:"+LISTENING_PORT);
connectionToServer = new Socket ("localhost", 2002);
TextIO.putln("Connected ");
long i=0;
while (i<2000000000) {
i++;
}
}
catch (Exception e) {
TextIO.putln("Sorry, the server has shut down.");
TextIO.putln("Error: "+e);
return;
}
}
}
客户端不会向服务器发送任何数据。
我在PC上启动了这两个程序。 客户印刷:
Localhost connects to:2002
Connected
Press any key to continue . . .
服务器打印:
Listening on port 2002
FdsfsdfsError: java.net.SocketException: Connection reset
为什么这个字符串 “Error: java.net.SocketException: Connection reset
” 打印服务器的控制台上很明显。 但我不知道这是什么意思:“Fdsfsdfs
”? 我可以防止打印这个字符串“Fdsfsdfs
”吗?
感谢您的回答。这真的很有用! –