我在Java中使用Socket进行简单的客户端/服务器聊天。问题是程序相互连接但由于某些原因我无法从双方获取/接收数据。当我断开服务器时,客户端给我一个错误“连接重置”,表明它们已连接,但它们不交换数据。
代码与从here获取的Java Tutorial中的代码相同。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
/**
*
* @author Amr
*/
import java.net.*;
import java.io.*;
public class KnockKnockServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4440);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
System.out.println(Inet4Address.getLocalHost());
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String inputLine, outputLine;
while ((inputLine = in.readLine()) != null) {
outputLine = "heelo";
out.println(outputLine);
if (outputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
}
import java.io.*;
import java.net.*;
public class KnockKnockClient {
public static void main(String[] args) throws IOException {
Socket kkSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
kkSocket = new Socket(Inet4Address.getLocalHost(), 4440);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis.");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis.");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String fromServer;
String fromUser;
while ((fromServer = in.readLine()) != null) {
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
fromUser = stdIn.readLine();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
out.close();
in.close();
stdIn.close();
kkSocket.close();
}
}
答案 0 :(得分:5)
设置连接后,服务器首先做的是
while ((inputLine = in.readLine()) != null)
也就是说,它等待客户说些什么。
您的客户做的第一件事就是
while ((fromServer = in.readLine()) != null)
也就是说,它等待服务器说些什么。
让两个中的一个先发送一些东西然后就可以了。
答案 1 :(得分:2)
该教程中缺少的是这个块:
// initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);
目前,您没有初始化对话,因此其他海报指出了套接字读取阻止。
答案 2 :(得分:1)
客户端和服务器上都有一个单独的线程,使用阻止的readLine()
方法从各自的BufferedReader
读取。
由于客户端和服务器都希望在之前之前读取任何内容,因此它们都只是坐在那里阻止。您需要fork并拥有一个从BufferedReader
读取的线程和一个写入PrintWriter
的线程,或者您必须拥有:
outputLine = "heelo";
out.println(outputLine);
在你的while循环之外。