我用Java创建了一个套接字 此套接字与服务器连接。
当我启动程序时,服务器会发送一条消息,说明我的套接字与AEOS连接。
当我尝试登录服务器发送一些命令时,服务器再次响应:status connected to AEOS version
这不是我期望的消息,通常我的服务器必须发送"响应为真"。
你能帮帮我吗?感谢。
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
while(true) {
String sentence;
String modifiedSentence;
Socket clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
}
答案 0 :(得分:0)
为什么不尝试阅读服务器发送的所有内容?另外,每次都需要打开一个新的Socket吗?取决于您的实施。试试这个:
public static void main(String[] args) {
Socket clientSocket = null;
try {
clientSocket = new Socket("127.0.0.1", 1201);
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
DataOutputStream outToServer = new DataOutputStream(
clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String initialMessageFromServer = null;
while ((initialMessageFromServer = inFromServer
.readLine()) != null) {
System.out.println(initialMessageFromServer);
}
while (true) {
String sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
StringBuilder modifiedSentence = new StringBuilder();
String responseFromServer = null;
while ((responseFromServer = inFromServer.readLine()) != null) {
modifiedSentence.append(responseFromServer);
modifiedSentence.append('\n');
}
System.out
.println("FROM SERVER: " + modifiedSentence.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}