import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.Socket;
/**
* 请求tcp接口
*
* @author Mr丶s
* @date 2024/7/10 下午3:03
* @description
*/
@Slf4j
@Service
public class TcpClientService {
private Socket socket;
private PrintWriter out;
private BufferedReader in;
/**
* 创建链接
*
* @param ip
* @param port
*/
public synchronized void startConnection(String ip, int port) {
if (socket == null || socket.isClosed()) {
try {
socket = new Socket(ip, port);
out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
/**
* 发送消息
*
* @param message
* @return
* @throws Exception
*/
public synchronized String sendMessage(String message) {
String response = null;
try {
if (socket == null || socket.isClosed()) {
throw new IllegalStateException("Connection is closed. Please start the connection first.");
}
out.println(message);
response = in.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return response;
}
/**
* 关闭链接
*
* @throws Exception
*/
public synchronized void stopConnection() throws Exception {
if (socket != null && !socket.isClosed()) {
in.close();
out.close();
socket.close();
}
}
/**
* 判断链接是否在线
*
* @return
*/
public boolean isConnectionActive() {
return socket != null && !socket.isClosed();
}
}
springboot下 创建TCP客户端,并发送消息
于 2024-07-11 10:20:05 首次发布