如何从插座上阅读JSON?爪哇

发布于 2025-02-13 17:40:42 字数 1200 浏览 0 评论 0原文

我正在做服务器/客户端网络。消息作为JSON对象发送。 我有一种编写JSON-Object的方法,但是我读取JSON-Object的方法无效。我没有任何例外,但是没有像挖掘的输出。 BufferedReader一定有问题。我不知道如何从发送它的插座上获取JSON-OBJECT。 写作方法:

public void writeMessage(JSONObject json) {
        try {
            PrintWriter printWriter = new PrintWriter(
                    new OutputStreamWriter(
                            socket.getOutputStream())); 
            printWriter.print(json);
            printWriter.flush();

        } catch (IOException writeMessageException) {
            System.out.println("!");

        }
    }

阅读消息/接收消息的方法:

private static void readMessageFromServer(Socket socket) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) 
    {
         StringBuilder sb = new StringBuilder();
            String readLine;
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            JSONObject js = new JSONObject(sb.toString());
        String action1 = (String) js.get("action1");
    System.out.println(action1);
    } catch(IOException e) {
        System.out.println("!");
    }
    }

谢谢:)

I am doing a Server/Client network. The messages are send as Json Objects.
I have a method for writing the Json-Object but my method for reading the Json-Object doesnt work. I dont have any exceptions but there is no output like excpected. Something must be wrong with the bufferedReader. I dont know how to get that Json-Object from the socket who sent it.
Method for writing:

public void writeMessage(JSONObject json) {
        try {
            PrintWriter printWriter = new PrintWriter(
                    new OutputStreamWriter(
                            socket.getOutputStream())); 
            printWriter.print(json);
            printWriter.flush();

        } catch (IOException writeMessageException) {
            System.out.println("!");

        }
    }

method for reading the message/ receiving the message:

private static void readMessageFromServer(Socket socket) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()))) 
    {
         StringBuilder sb = new StringBuilder();
            String readLine;
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            JSONObject js = new JSONObject(sb.toString());
        String action1 = (String) js.get("action1");
    System.out.println(action1);
    } catch(IOException e) {
        System.out.println("!");
    }
    }

Thank you :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

知足的幸福 2025-02-20 17:40:42
  1. 考虑使用Javax Websocket

.并指定您期望使用pojos接收的类型参数。

    @Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<MyJsonObject>() {

        @Override
        public void onMessage(MyJsonObject message) {
        //do something
        }
    });
}

这样,您就可以创建一个侦听器(@OnMessage)并在收到的每条消息后立即处理。您还可以使用字符串类型参数来实现MessageHandler,并在onMessage方法中处理自己的JSON自己解析;

@Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String message) {
            MyJsonObject jObj = new ObjectMapper().readValue(message, MyJsonObject.class);
        }
    });
}
  1. 如果您想坚持使用Java Net插座,请考虑切换到杰克逊对象映射器从jsonobject中,这样您就可以将输入流转换为任何对象:

     私有静态void readmessageFromServer(套接字插座){
            inputStream in = socket.getInputStream();
            myObject obj = new ObjectMapper()。readValue(in,MyObject.Class); 
         }
     

更多javax websocket 示例

  1. Consider using javax websocket.

javax.websocket client simple example

You can simply implement MessageHandler and specify the type parameter you expecting to receive using POJOs.

    @Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<MyJsonObject>() {

        @Override
        public void onMessage(MyJsonObject message) {
        //do something
        }
    });
}

That way you are creating a listener (@OnMessage) and handling each message as soon as it received. You can also implement MessageHandler with String type parameter and handle parsing the json yourself inside OnMessage method;

@Override
public void onOpen(Session session, EndpointConfig config) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

        @Override
        public void onMessage(String message) {
            MyJsonObject jObj = new ObjectMapper().readValue(message, MyJsonObject.class);
        }
    });
}
  1. If you want to stick with java net socket consider switching to Jackson Object Mapper from JSONObject, that way you can convert input stream into any object:

         private static void readMessageFromServer(Socket socket){
            InputStream in = socket.getInputStream();
            MyObject obj = new ObjectMapper().readValue(in, MyObject.class); 
         }
    

more javax webSocket examples

怪我闹别瞎闹 2025-02-20 17:40:42

读取字节中的数据时,我们需要定义自己的协议,以进行服务器和客户端之间的通信。最简单的协议
我们可以定义称为TLV(类型长度值)。这意味着每个
*写入套接字的消息是类型长度值的形式 *。

因此,我们将发送的每个消息定义为:

代表数据类型的1个字节字符,例如字符串a
4指示数据长度的字节整数,然后
实际数据,其长度仅表示

DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
char dataType = in.readChar();
int length = in.readInt();
    if(dataType == 's') {
        byte[] messageByte = new byte[length];
        boolean end = false;
        StringBuilder dataString = new StringBuilder(length);
        int totalBytesRead = 0;
        while(!end) {
            int currentBytesRead = in.read(messageByte);
            totalBytesRead = currentBytesRead + totalBytesRead;
            if(totalBytesRead <= length) {
                dataString
                  .append(new String(messageByte, 0, currentBytesRead, StandardCharsets.UTF_8));
            } else {
                dataString
                  .append(new String(messageByte, 0, length - totalBytesRead + currentBytesRead, 
                  StandardCharsets.UTF_8));
            }
            if(dataString.length()>=length) {
                end = true;
            }
        }
    }

更多的详细信息可以在此处找到
https://wwwww.baeldung.com/java-input--inputstream-server-server-server-server-server-server-server-server-server-server-server-sercock

When reading data in bytes, we need to define our own protocol for communication between server and client. The simplest protocol which
we can define is called TLV (Type Length Value). It means that every
*message written to the socket is in the form *of the Type Length Value.

So we define every message sent as:

A 1 byte character that represents the data type, like s for String A
4 byte integer that indicates the length to the data And then the
actual data, whose length was just indicated

DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
char dataType = in.readChar();
int length = in.readInt();
    if(dataType == 's') {
        byte[] messageByte = new byte[length];
        boolean end = false;
        StringBuilder dataString = new StringBuilder(length);
        int totalBytesRead = 0;
        while(!end) {
            int currentBytesRead = in.read(messageByte);
            totalBytesRead = currentBytesRead + totalBytesRead;
            if(totalBytesRead <= length) {
                dataString
                  .append(new String(messageByte, 0, currentBytesRead, StandardCharsets.UTF_8));
            } else {
                dataString
                  .append(new String(messageByte, 0, length - totalBytesRead + currentBytesRead, 
                  StandardCharsets.UTF_8));
            }
            if(dataString.length()>=length) {
                end = true;
            }
        }
    }

More detail info can be found here
https://www.baeldung.com/java-inputstream-server-socket

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文