“This is the ninth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

How does Socket TCP pass strings and byte arrays

We can carry out two-way communication through Socket TCP. When we use chat tool to chat, we can not only send text, but also send pictures. How to achieve this, and how to distinguish between text and picture?

nature

All the data on a computer is, in the final analysis, made up of zeros and ones, and whatever data we send must eventually be converted into zeros and ones for storage.

In Java, our smallest operation is in bytes, so whenever we send an image or text, we send it through an array of bytes.

String implementation

Methods a

Server: Each time data is sent, a newline character is spelled at the end of the data.

public void sendString(final String msg) { new Thread(new Runnable() { @Override public void run() { synchronized (LOCK) String data = MSG + "\n"; out.write(data.getBytes()); // Force out.flush(); } catch (IOException e) { e.printStackTrace(); } } } }).start(); }Copy the code

Client: Use the readLine method

Private void startReceiveTcpThread() {threadPool.getInstance ().execute(new Runnable() {@override Public void run() {// Get data String line = ""; try { while ((line = br.readLine()) ! = null) { handleReceiveTcpMessage(line); } if (line == null) {LogWrapper. E (TAG, "line == null..." ); disConnect(); }} catch (IOException e) {e.printStackTrace(); // LogWrapper. E (TAG, "failed to receive message, started to disconnect... : "+ e. oString ()); disConnect(); }}}); }Copy the code

Method 2

Gets an array of bytes, which goes to String.

InputStream InputStream = socket.getinputStream (); byte[] buf = new byte[1024]; int len = inputStream.read(buf); String textString = new String(buf, 0, len); System.out.println(textString); socket.close();Copy the code

Accepts both strings and byte arrays

Since the readLine method reads a newline, this definitely won’t work; We’re going to try the second approach, at the sending end, to try to distinguish between types. Such as

The sender:

Define two different constants as markers to distinguish between different types

final byte BYTE_TYPE = 0x1; final byte STRING_TYPE = 0x2; Write (BYTE_TYPE); // byte Array type out.write(BYTE_TYPE); out.write(bytes); // String type out.write(STRING_TYPE); out.write(string.getBytes());Copy the code

The receiver:

Extract the type and act accordingly

private void startReceiveTcpThread() { ThreadPool.getInstance().execute(new Runnable() { @Override public void run() { while (true) { try { byte[] bytePacket = new byte[BUFFER_LENGTH]; int actLength = mSocket.getInputStream().read(bytePacket); byte[] actPacket = new byte[actLength]; System.arraycopy(bytePacket, 0, actPacket, 0, actLength); int type = actPacket[0]; If (type == BYTE_TYPE){// If (type == BYTE_TYPE){// If (type == STRING_TYPE){... // Get rid of the first type, then convert new String(); } } catch (IOException e) { e.printStackTrace(); }}}}); }Copy the code

Byte [] bytePacket = new byte[BUFFER_LENGTH]. The correct way to set BUFFER_LENGTH is to fix BUFFER_LENGTH and merge the packet.

Subcontracting and contracting will be discussed in the next article.