JAVA Socket realizes receiving TCP messages in real time, making your server communication more efficient!

This article mainly introduces how to use socket to receive TCP messages sent by the server in real time.

Table of contents

1. Need to master

2. Program source code

3. Run the demo

1. Need to master

Network debugging assistant download: https://www.aliyundrive.com/s/6Y8L7Wv5sT6

Understanding of network communication protocols: JAVA socket is implemented based on the TCP/IP protocol, and requires a certain understanding of the TCP/IP protocol, including the establishment of TCP connections, data transmission, and disconnection.

1. Implementation of multi-threaded programming: In order to receive TCP messages sent by the server in real time, it is necessary to use a multi-threaded programming mode in the client program, and place data reception and data processing in different threads.

2. Analysis of data format: the client needs to be able to correctly parse the TCP message sent by the server, including the message format, encoding method, etc., and also needs to consider error handling and exception handling.

3. Data caching and processing: Due to the uncertainty of network communication, the client needs to implement data caching and processing to ensure the integrity and accuracy of the data, and to be able to quickly respond to the messages sent by the server.

4. Security considerations: In the process of receiving TCP messages sent by the server in real time, data security needs to be considered, including data encryption and data tamper prevention.

2. Program source code

package com.vblog.web.controller.system;
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
 * @author Roc-xb
 */
public class TcpClient {
	/**
     * 主函数
     */
	public static void main(String[] args) {
		while (true) {
			try {
				InputStream is;
				// 创建Socket对象,连接到指定的IP地址 和端口号
				Socket socket = new Socket("127.0.0.1", 9001);
				if (socket.isConnected()) {
					System.out.println("socket连接成功:" + socket);
				}
				// 定义缓冲区
				byte[] buff = new byte[1024];
				// 设置读取数据的超时时间为10秒
				socket.setSoTimeout(10000);
				// 获取输入流
				is = socket.getInputStream();
				while (true) {
					try {
						// 读取数据
						int readlen = 0;
						if (is != null) {
							readlen = is.read(buff);
						}
						// 将读取到的数据复制到一个新的数组中
						byte[] data = Arrays.copyOfRange(buff, 0, readlen);
						// 解析数据
						resolveData(data);
					}
					catch (SocketTimeoutException e1) {
						System.out.println("等待TCP Server响应数据...");
					}
					catch (Exception e2) {
						System.out.println("TCP Server已断开连接...");
						break;// 作用:避免TCP服务器断开的时候,进入死循环
					}
				}
			}
			catch (ConnectException e4) {
				System.out.println("TCP Server处于离线状态...");
			}
			catch (Exception e5) {
				System.out.println("其它异常信息:" + e5.getMessage());
			}
		}
	}
	public static String convertGBKToUTF8(String strGBK) {
		Charset gbkCharset = Charset.forName("GBK");
		Charset utf8Charset = Charset.forName("UTF-8");
		byte[] gbkBytes = strGBK.getBytes(gbkCharset);
		byte[] utf8Bytes = new String(gbkBytes, utf8Charset).getBytes(utf8Charset);
		return new String(utf8Bytes, utf8Charset);
	}
	/**
     * 解析数据
     *
     * @param data 待解析的数据
     */
	private static void resolveData(byte[] data) {
		// 将字节数组转换为字符串
		String message = new String(data);
		// 对接收到的数据进行解析处理
		System.out.println("服务器发送过来的数据包: " + message);
	}
}

3. Run the demo

 The above code has realized that the TCP client can obtain the message sent by the TCP server in real time, and can perceive the online/offline status of the TCP server.

Guess you like

Origin blog.csdn.net/qq_19309473/article/details/131028283