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;
@Slf4j
@Service
public class TcpClientUtils {private SocketChannel socketChannel;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();}}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.open();socketChannel.connect(new InetSocketAddress("47.114.51.90", 18888));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();}}
}