gpt4 book ai didi

java - 简单的Java网络程序

转载 作者:行者123 更新时间:2023-12-01 20:54:25 25 4
gpt4 key购买 nike

我是 Java 编程新手,我只是想让一个非常基本的网络程序能够工作。

我有 2 个类,一个客​​户端和一个服务器。这个想法是客户端简单地向服务器发送一条消息,然后服务器将消息转换为大写并将其发送回客户端。

我在让服务器向客户端发送消息方面没有任何问题,问题是我似乎无法将客户端发送的消息存储在变量服务器端以便对其进行转换,因此可以'不要发回该特定消息。

这是我到目前为止的代码:

服务器端

     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();
}
}

我认为问题可能出在“String word = 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

关于java - 简单的Java网络程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42611876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com