java - 简单的Java网络程序

标签 java string

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

相关文章:

java - 使用 EMV 芯片读取信用卡并将数据写入基于 Web 浏览器的 POS 屏幕

java - Camel Route 到 XMPP 聊天室惨败

java - 如何找出哪个 Activity 启动了触发您的 BroadCastReceiver 的 Intent ?

java - 如何根据微调器值将音频保存在SD卡中

python - 用随机生成的数字替换字符串的一部分

java - 无法使用 Caffeine 创建简单缓存

java - JList 文件夹中所有文件名

java - 删除字符串的一部分

java - Java中如何删除字符串开头的空格而不是制表符?

java - 搜索字符串只打印出没有附加字符的搜索