实现tcp通信,一般第一想到的是用netty框架,但是netty实现的通信一般是异步,发送消息后,不需要等到回复。
最近遇到一个需求时,与某个网关进行tcp通信,发送请求消息之后会立马回复,并且不同的请求命令,返回的回复数据内容也不相同。思考再三,决定不使用netty,使用socket进行通信,请求后等到回复,收到回复内容进行解析。
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.HexUtil;import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;public class TCPClient {public static Map<String, Socket> ipChannelMap = new ConcurrentHashMap<String, Socket>();public static void main(String[] args) {try {//连接服务器Socket socket = new Socket("192.168.11.11", 8889);//发送指令String request = "12313112";OutputStream out = socket.getOutputStream();out.write(HexUtil.decode(request));out.flush();//接收服务器返回指令InputStream in = socket.getInputStream();byte[] buffer = new byte[1024];int len = in.read(buffer);String response = new String(buffer, 0, len);String hexString = HexUtil.encodeToString(response);System.out.println("Client received: " + hexString);//断开服务器socket.close();} catch (IOException e) {e.printStackTrace();}}/*** @Title createSocket* @Description 建立socket连接* @param ip* @param port* @Author ju* @Return java.net.Socket* @Date: 2023/12/22 14:26*/public static Socket createSocket(String ip,int port){//连接服务器Socket socket = null;try {socket = ipChannelMap.get(ip + ":" + String.valueOf(port));if (Func.isNull(socket)){socket = new Socket(ip, port);ipChannelMap.put(ip + ":" + String.valueOf(port),socket);}} catch (IOException e) {e.printStackTrace();}return socket;}/*** @Title destroyConnect* @Description 断开socket连接* @param socket* @Author ju* @Return void* @Date: 2023/12/22 14:27*/public static void destroyConnect(Socket socket){try {socket.close();} catch (IOException e) {e.printStackTrace();}}/*** @Title send* @Description 发送请求指令并返回服务器的返回指令* @param socket* @param request* @Author ju* @Return java.lang.String* @Date: 2023/12/22 14:27*/public static String send(Socket socket,String request){String response = "";try {OutputStream out = socket.getOutputStream();out.write(HexUtil.decode(request));out.flush();//接收服务器返回指令InputStream in = socket.getInputStream( );byte[] buffer = new byte[1024];int len = in.read(buffer);String str = new String(buffer, 0, len);response = HexUtil.encodeToString(str);System.out.println("Client received: " + response);} catch (IOException e) {e.printStackTrace();}return response;}
}