Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use TCP Communication and Transport Protocol in Java back-end Development

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use TCP communication transmission protocol in Java back-end development. Xiaobian thinks it is quite practical, so share it with you as a reference. I hope you can gain something after reading this article.

ServerSocket --Listen for client connections, its role is mainly to establish a connection

-ServerSocket -Establish a connection and get a Socket

-Telnet 127.0.0.1 8888-Client uses Telnet to access server to establish connection

- The server can get a Socket object

- Get the input and output streams of this object

- Write and read data

Socket connection model

The server and client are connected through Socket. Although it is a Socket, it is equivalent to dividing this Socket into two pipes. The server holds one section of these two pipes, and the client holds the other end of these two pipes.

Server input connected to client output

The client sends data, from the Client output to the Server input

The server sends data from the output of the Server to the input of the Client.

If two-port communication is implemented, each program needs at least two threads.

Message Protocol

TCP: connection-oriented

UDP: No need to establish a connection-like datagram

TCP: Stable, requires confirmation that both parties can send and receive messages before sending data

Connection process: three-way handshake

Server--------------------- Client

1: Listening-----------------------

After this step, the server knows that the client can send data.

2: Receive request, reply-------------Receive reply message, send reply packet to s

After this step, the client knows that the server can send and receive data

3: Acknowledgement received

After this step, the server knows that the client can receive data.

Details to know about data types during transmission

char: 16bit two bytes

Unit of data transmission: data is transmitted one byte at a time, and a char needs to be transmitted twice.

Send a text message

The first part should send the length of the string to determine the length of the byte array

The first byte read is the message length, defining a container with a fixed capacity.

The second part is the message content

The other party reads bytes of corresponding length and converts them into corresponding data (String object).

Data Type:

integer: byte short int long

Floating point type: float double

Character type: char

Boolean: boolean

char=16bit=2 byte unicode encoding

utf-8:1-6 bytes constitute a Chinese character

1100 1101 1010

If the first byte of this data has two 1's, it means that it is a man, and the next two bytes represent this Chinese character. If there is 111, read the next three bytes.

Because ASCII code is used to store 0-127 in English, the first bit cannot be 1, and it can be judged whether it is Chinese or English by the first byte

All English letters compatible: ASCII 0-127 Binary code: 0-255, so 0-127 must start with 0, Chinese characters are 16bit 0-65536

TCP communication code

By writing a client and a server by myself, the initial launch of the message is realized. The core here is mainly to write the communication protocol by myself. The first time I send it here is the length of the data, and the data is encrypted. The client needs to parse the data length and create an array of corresponding lengths in order to correctly read the message content.

MsgClient

package com.lding.net;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;import java.util.Scanner;/** * @program: Net * @description: Tcp Client Test * @author: Wang Ding * @date: 2021-09-20 10:04 **/public class TcpClient { public static void main(String[] args) throws IOException { Socket socket=new Socket("127.0.0.1",8888); OutputStream output=socket.getOutputStream(); InputStream input=socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(input);// byte[] msgbyte=new byte[30];// input.read(msgbyte);// System.out.println("Server says: "+new String(msgbyte)); int length2=input.read(); int length3=input.read(); int msglength=length3*3+length2; System.out.println("Message length is: "+ mslength); byte[] msgbytes=new byte[msglength]; input.read(msgbytes); String getmsg=new String(msgbytes); System.out.println("Server says: "+getmsg); }}

MsgServer

package com.lding.net;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;/** * @program: Net * @description: TCP Server Test * @author: Wang Ding * @date: 2021-09-20 10:03 **/public class TcpServer { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(8888); //Listen for Socket connections on the client System.out.println("Server open: ip: "+serverSocket.getInetAddress().getHostAddress()+"Port number: "+serverSocket.getLocalSocketAddress()); System.out.println("Waiting for someone... "); Socket socketClient = serverSocket.accept(); System.out.println("Client connected: "+socketClient.getInetAddress()); System.out.println("client port"+socketClient.getPort()); OutputStream output=socketClient.getOutputStream(); InputStream input=socketClient.getInputStream();// output.write("Server connection successful!!! ".getBytes());// output.flush();//flush buffer, forced pipeline flush String msg="Server connection successful!!! Happy Mid-Autumn Festival! using namespace std"; byte[] msgBytes=msg.getBytes(); int length2=msgBytes.length%3; int length3=msgBytes.length/3; output.write(length2); output.write(length3); output.write(msgBytes); output.flush();// while(input.read()!=- 1){// System.out.println((char) input.read());// } }}

operation results

that could be perfected.

1. After that, the communication protocol can be added to forward the message content to multiple clients through the client list

2. Carry user name, target user name, etc.

About "Java backend development TCP communication transmission protocol how to use" this article is shared here, I hope the above content can be of some help to everyone, so that you can learn more knowledge, if you think the article is good, please share it to let more people see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report