![](/img/trans.png)
[英]Java simple networking program works in Eclipse, not in terminal
[英]Simple Java Networking Program
我是Java編程的新手,我只是想嘗試一個非常基本的網絡程序。
我有兩個類,一個客戶端和一個服務器。 想法是,客戶只需將消息發送到服務器,然后服務器將消息轉換為大寫字母,然后將其發送回客戶端。
我在讓服務器向客戶端發送消息方面沒有問題,問題是我似乎無法將客戶端發送的消息存儲在變量服務器端以進行轉換,因此無法發送該消息具體消息回。
到目前為止,這是我的代碼:
服務器端
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket (9091);
while (true) {
System.out.println("Waiting");
//establish connection
Socket client = server.accept();
System.out.println("Connected " + client.getInetAddress());
//create IO streams
DataInputStream inFromClient = new DataInputStream(client.getInputStream());
DataOutputStream outToClient = new DataOutputStream(client.getOutputStream());
System.out.println(inFromClient.readUTF());
String word = inFromClient.readUTF();
outToClient.writeUTF(word.toUpperCase());
client.close();
}
}
}
客戶端
public class Client {
public static void main(String[] args) throws IOException {
Socket server = new Socket("localhost", 9091);
System.out.println("Connected to " + server.getInetAddress());
//create io streams
DataInputStream inFromServer = new DataInputStream(server.getInputStream());
DataOutputStream outToServer = new DataOutputStream(server.getOutputStream());
//send to server
outToServer.writeUTF("Message");
//read from server
String data = inFromServer.readUTF();
System.out.println("Server said \n\n" + data);
server.close();
}
}
我認為問題可能出在“字符串單詞= inFromClient.readUTF();” 線? 有人可以請教嗎? 謝謝。
您正在丟棄從客戶端收到的第一個數據包:
System.out.println(inFromClient.readUTF()); // This String is discarded
String word = inFromClient.readUTF();
為什么不交換這些?
String word = inFromClient.readUTF(); // save the first packet received
System.out.println(word); // and also print it
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.