import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;/*** 请求tcp接口** @author Mr丶s* @date 2024/7/10 下午3:03* @description*/
@Slf4j
@Service
public class TcpClientUtils {private SocketChannel socketChannel;/*** 创建通道** @param host* @param port* @return*/public String connect(String host, int port) {try {if (socketChannel == null || !socketChannel.isConnected() || !socketChannel.isOpen()) {socketChannel = SocketChannel.open();socketChannel.connect(new InetSocketAddress(host, port));return "Connection successful";} else {return "Already connected";}} catch (IOException e) {e.printStackTrace();return "Connection failed: " + e.getMessage();}}/*** 关闭通道*/public void closeConnection() {try {if (socketChannel != null && socketChannel.isOpen()) {socketChannel.close();}} catch (IOException e) {e.printStackTrace();}}/*** 发送消息** @param host* @param port* @param message* @return*/public String sendMessage(String host, int port, String message) {String response = "";try {if (socketChannel == null || !socketChannel.isConnected() || !socketChannel.isOpen()) {String connectionStatus = connect(host, port);if (!"Connection successful".equals(connectionStatus)) {return "Failed to connect: " + connectionStatus;}}// 发送数据ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());socketChannel.write(buffer);// 读取响应ByteBuffer responseBuffer = ByteBuffer.allocate(1024);socketChannel.read(responseBuffer);responseBuffer.flip();// 输出响应数据StringBuilder stringBuilder = new StringBuilder();while (responseBuffer.hasRemaining()) {stringBuilder.append((char) responseBuffer.get());}response = stringBuilder.toString();log.info("TCP 请求返回: " + response);} catch (IOException e) {e.printStackTrace();response = "Failed to send message: " + e.getMessage();}return response;}public static void main(String[] args) {try {// 创建SocketChannelSocketChannel socketChannel = SocketChannel.open();// 连接服务器socketChannel.connect(new InetSocketAddress("47.114.51.90", 18888));// 发送数据// String message = "P*Hello, Server!*B*K\n";String message = "P*1*55*21*240321002*1*0*8*0*0*0*1722496736654*1*240314002*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*0*B*K\n";ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());socketChannel.write(buffer);// 读取响应ByteBuffer responseBuffer = ByteBuffer.allocate(1024);socketChannel.read(responseBuffer);responseBuffer.flip();// 输出响应数据while (responseBuffer.hasRemaining()) {System.out.print((char) responseBuffer.get());}// 关闭连接socketChannel.close();} catch (IOException e) {e.printStackTrace();}}
}
Spingboot请求tcp 方式
2025/4/29 10:13:41
来源:https://blog.csdn.net/Mr1shuai/article/details/140848894
浏览:
次
关键词:Spingboot请求tcp 方式
版权声明:
本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。
我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com