Hello stackoverflow社区,
我遇到了有关Java中套接字通信的问题。
以下是我的服务器和客户端类的示例代码:
服务器:
public class OTPServer {
static ServerSocket serverSocket;
final static int PORT = 4242;
static Socket clientConnection;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Socket initialized");
String serverMessage = "Hello, I am the Host";
ServerTool serverTool = new ServerTool();
while (true) {
clientConnection = serverSocket.accept();
if(clientConnection.isConnected()) {
System.out.println("Client connected");
}
BufferedReader clientInputReader = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(clientConnection.getOutputStream());
System.out.println("Sending message to client: " + serverMessage);
serverOutput.writeBytes(serverTool.encodeMessage(serverMessage));
serverOutput.flush();
String clientMessage = clientInputReader.readLine();
System.out.println("Encoded answer from client: " + clientMessage);
String decodedMessage = serverTool.decodeMessage(clientMessage);
System.out.println("Decoded answer from client: " + decodedMessage);
serverOutput.close();
clientInputReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Hello, I am the OTP Server!");
}
以下是客户:
public class OTPClient {
static Socket clientSocket;
final static int PORT = 4242;
final static String HOST = "localhost";
public static void main(String[] args) {
System.out.println("I am the OTP Client!");
String serverMessage;
String clientResponse = "I am the Client";
OTPTool otpTool = new OTPTool();
try {
clientSocket = new Socket(HOST, PORT);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Connection to Host established");
serverMessage = serverInput.readLine();
System.out.println("Encoded Message from Server: " + serverMessage);
String decodedMessage = otpTool.decodeMessage(serverMessage);
System.out.println("Decoded message from Server: " + decodedMessage);
System.out.println("Answering with own message: " + clientResponse);
outputStream.writeBytes(clientResponse);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
现在我的问题在哪里:
连接建立,服务器似乎将其消息发送到客户端并等待答复。客户端不会打印从服务器获取的消息。 一旦我取消服务器,客户端就会打印出从服务器获取的消息以及发送答案的信息,退出代码为0,因此看起来这部分很好,只是卡在某种程度上。 我已经尝试刷新outputStream,就像在给出的示例代码中看到的那样。
是否有一些明显的遗失? 我知道,这是非常基本的东西,但它是我第一次使用套接字进行通信。
提前谢谢!
最诚挚的问候, 罗尼
顺便说一句:我知道服务器只连接到一个请求连接的客户端。这绝对足以让我使用。
答案 0 :(得分:1)
它会卡住,因为serverInput.readLine();
会阻塞,直到遇到换行符或文件结尾。在服务器端,您没有发送换行符,因此客户端阻止。