我是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

07-27 22:44