我从 java 套接字开始,并且有奇怪的[缺乏]输出。这是我的套接字方法的来源:
客户端源码:
public void loginToServer(String host, String usnm ) {
try {
Socket testClient = new Socket(host,1042);
System.out.println ("Connected to host at " + host);
logString = ("CONNECTED: " + host);
outGoing = new PrintWriter(testClient.getOutputStream(), true);
outGoing.print("Hello from " + testClient.getLocalSocketAddress());
InputStream inFromServer = testClient.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readLine());
testClient.close();
}
catch (Exception e) {
System.err.println ("Error connecting to host at " + host + ":1042.\n Reason: " + e);
logString = ("CONNECT FAILED: " + host + ":1042: " + e);
}
printLog(logString);
// send server usnm and os.name [System.getProperty(os.name)] ?
}
以及服务器代码:
public void runServer() {
try{
server = new ServerSocket(1042);
}
catch (IOException e) {
printLog("LISTEN FAIL on 1042: " + e);
System.err.println("Could not listen on port 1042.");
System.exit(-1);
}
try{
client = server.accept();
}
catch (IOException e) {
printLog("ACCEPT FAIL on 1042: " + e);
System.err.println("Accept failed: 1042");
System.exit(-1);
}
try{
inComing = new BufferedReader(new InputStreamReader(client.getInputStream()));
outGoing = new PrintWriter(client.getOutputStream(), true);
}
catch (IOException e) {
printLog("READ FAIL on 1042: " + e);
System.err.println("Read failed");
System.exit(-1);
}
while(true){
try{
clientData = inComing.readLine();
//processingUnit(clientData, client);
outGoing.print("Thank you for connecting to " + server.getLocalSocketAddress() + "\nGoodbye!");
}
catch (IOException e) {
printLog("READ FAIL on 1042: " + e);
System.out.println("Read failed");
System.exit(-1);
}
}
}
客户给出的输出只是Connected to host at localhost
.
这是怎么回事?
您正在读取行,但没有发送行。改变print()
to println()
. readLine()
将永远阻塞等待换行符。它将在流结束时返回 null,即当对等方关闭连接时,但您也没有检查这一点,因此您无限循环。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)