TcpClientService.java
1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.huaheng.pc.config.sn.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();
    }
}