springboot下 创建TCP客户端,并发送消息


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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值