Spingboot请求tcp 方式


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 {
            // 创建SocketChannel
            SocketChannel 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();
        }
    }
}
  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java自带的Socket类或者第三方库Netty来发送TCP请求。以下是使用Socket类发送TCP请求的示例代码: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class TcpClient { public static void main(String[] args) { String host = "localhost"; int port = 8080; try { Socket socket = new Socket(host, port); OutputStream outputStream = socket.getOutputStream(); String message = "Hello, TCP server!"; outputStream.write(message.getBytes()); outputStream.flush(); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); String response = new String(buffer, 0, len); System.out.println("Server response: " + response); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在Spring Boot中,可以将TCP请求封装为一个服务或者组件,然后在需要的地方注入调用。例如: ```java import org.springframework.stereotype.Component; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; @Component public class TcpClient { private final String host = "localhost"; private final int port = 8080; public String send(String message) { try { Socket socket = new Socket(host, port); OutputStream outputStream = socket.getOutputStream(); outputStream.write(message.getBytes()); outputStream.flush(); InputStream inputStream = socket.getInputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); String response = new String(buffer, 0, len); socket.close(); return response; } catch (IOException e) { e.printStackTrace(); } return null; } } ``` 然后在需要发送TCP请求的地方,可以通过注入TcpClient服务来发送请求: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MyController { @Autowired private TcpClient tcpClient; @GetMapping("/tcp") public String sendTcpRequest() { String message = "Hello, TCP server!"; String response = tcpClient.send(message); return "Server response: " + response; } } ``` 当访问 /tcp 接口时,会发送 TCP 请求并返回响应结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值