Rapsssito / react-native-tcp-socket

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support.
MIT License
321 stars 82 forks source link

JSON Server data convert #2

Closed snapxtp closed 5 years ago

snapxtp commented 5 years ago

Hello i added an plugini and ran an application. Thank you.

Server is running and listening in this application...

I can see output when I send a post request with postman.

In the following code, how can I make an incoming requestin format in json and how to extract a json sent from an incoming query ?

server = TcpSocket.createServer((socket) => {
            this.updateChatter('server connected on ' + JSON.stringify(socket.address()));

            socket.on('data', (data) => {
             console.log(data)
                this.updateChatter('Server Received: ' + data);
            });
Rapsssito commented 5 years ago

This could be a way of doing it if you are only working with JSONs. However, it is a bit unsafe if you are getting two messages from the same socket too close in time.

socket.pool = '';
socket.on('data', (data) => {
      socket.pool += data;
       try {
            // Once the message is completed
            const response = JSON.parse(socket.pool);
            socket.pool = '';
            this.updateChatter('Server Received: ' + response);
       } catch (error) { } // Loop until the JSON is complete
});
snapxtp commented 5 years ago

Thanks for your quick answer. I guess I couldn't tell my question here. For example: 127.0.0.0:5556 creating a server. I'm sending a post request to this server with postman.

And the query falls here: socket.on('data', (data) => { console.log(data) });

data format: Uint8Array I would parse it and get the following output: I was wondering if I could convert the data content to json format and use it as data.body and just get the MySendData part.

POST / HTTP/1.1 User-Agent: PostmanRuntime/7.18.0 Accept: / Cache-Control: no-cache Postman-Token: 0203483a-b5ec-4c11-a3a0-a54daec0ce4c Host: 127.0.0.1:5556 Accept-Encoding: gzip, deflate Content-Length: 31 Connection: keep-alive

{ "MySendData":"DataContent" }

Rapsssito commented 5 years ago

Sorry, I didn't understand the question. socket.on('data') is called each time a byte or a bunch of bytes are received from the client socket. If you are planning to receive big chunks of data (like HTTP), you should think of socket.on('data') like a loop and create your logic around that. If you are only working with HTTP, you can use Content-Length: 31 to detect the size of the message and act accordingly.

However, since your question is outside the scope of this library, I would recommend you to ask it in StackOverflow.

zengkl520 commented 4 years ago

your questtion like websocket,not tcp-socket