我试图学习如何处理Java 8中的网络,并且我试图让客户端程序与服务器程序进行通信。客户端被询问一个字符串,该字符串被发送到服务器,服务器以高位字符发送回来。
我无法让我的服务器部分工作,除了建立连接之外,它根本不会写任何东西。有人可以解释我的代码有什么问题吗?
服务器:
public static void main(String[] args) throws IOException {
int listenPort = 9000;
ServerSocket listenSocket = new ServerSocket(listenPort);
Socket socket = listenSocket.accept();
System.out.println("Connexion réussie !");
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(inputStream));
DataOutputStream output = new DataOutputStream(outputStream);
String line = null;
System.out.println("test : " + buffer.readLine());
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + line);
System.out.println("Message envoyé : " + line.toUpperCase());
output.writeUTF(line.toUpperCase());
if(line.equals("stop")) {
socket.close();
listenSocket.close();
}
}
}
客户方:
public static void main(String[] args) throws IOException, UnknownHostException {
Socket socket = new Socket("127.0.0.1", 9000);
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
DataInputStream input = new DataInputStream(inputStream);
DataOutputStream output = new DataOutputStream(outputStream);
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line = buffer.readLine()) != null) {
System.out.println("Message envoyé : " + line);
output.writeChars(line);
System.out.println("Message reçu : " + input.readUTF());
if(line.equals("stop")) {
break;
}
}
socket.close();
}
答案 0 :(得分:0)
在您的客户端方法中,您在while循环中调用output.writeChars(line)
,这意味着您在服务器向您发送内容后向服务器发送内容。
按如下方式更改您的客户端代码:
String line = "What a wonderful line";
System.out.println("Message envoyé : " + line);
output.writeChars(line);
while((line = buffer.readLine()) != null) {
System.out.println("Message reçu : " + input.readUTF());
}