我是靠谱客的博主 单薄康乃馨,这篇文章主要介绍Java实现socket 客户端 长连接,现在分享给大家,希望可以做个参考。

Java实现socket客户端长连接

复制代码
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import com.teruisa.jinji100.utils.HexUtil; import com.teruisa.jinji100.utils.SocketUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.Socket; import java.net.UnknownHostException; /** * socket 长连接:连接建立后不会主动断开,可以持续收发消息 */ public class ClientThread { private final Logger logger = LoggerFactory.getLogger(ClientThread.class); private String hosts; private int port; private Socket socket = null; private OutputStream os = null; private InputStream is = null; public ClientThread(String hosts, int port) { this.hosts = hosts; this.port = port; try { this.socket = new Socket(hosts, port); this.os = socket.getOutputStream(); this.is = socket.getInputStream(); SocketThread socketThread = new SocketThread(); socketThread.start(); logger.info("创建socket连接成功,address:{}:{}", hosts, port); } catch (UnknownHostException e) { logger.error("创建socket连接UnknownHost异常", e); } catch (IOException e) { logger.error("创建socket连接IO异常", e); } } /** * 办公灯光 * @param msg * @return */ public String sendLampComd(String msg) { String receiveMsg = ""; PrintWriter pw = null; BufferedReader br = null; try { pw = new PrintWriter(os); pw.write(msg); pw.flush(); socket.shutdownOutput(); // 从服务器接收的信息 br = new BufferedReader(new InputStreamReader(is)); receive(br); } catch (IOException e) { logger.error("IOException", e); } finally { // 关闭资源 SocketUtil.close(br, null, is, os, socket); } return receiveMsg; } /** * 会议室灯光 * @param msg * @return */ public String sendMeetingComd(String msg) { byte[] data = HexUtil.hexStrToBinaryStr(msg); return sendCurtainComd(data); } /** * 窗帘 * @param data * @return */ public String sendCurtainComd(byte[] data) { String receiveMsg = ""; BufferedReader br = null; try { os.write(data); socket.shutdownOutput(); br = new BufferedReader(new InputStreamReader(is)); receive(br); } catch (IOException e) { logger.error("IOException", e); } finally { // 关闭资源 SocketUtil.close(br, null, is, os, socket); } return receiveMsg; } private String receive(BufferedReader br) throws IOException { // 从服务器接收的信息 String receiveMsg = ""; String reply; while((reply = br.readLine()) != null){ logger.info("设备中控返回信息:{}", reply); receiveMsg = reply; } return receiveMsg; } /** * 发送心跳包 */ /*public void sendHeartbeat() { try { String heartbeat = "pingrn"; new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(10 * 1000);// 10s发送一次心跳 os.write(heartbeat.getBytes()); os.flush(); } catch (Exception e) { logger.error("发送心跳异常", e); } } } }).start(); } catch (Exception e) { logger.error("发送心跳异常", e); } }*/ private class SocketThread extends Thread { @Override public void run() { long startTime = System.currentTimeMillis(); //sendHeartbeat(); while (true) { try { if (socket == null || socket.isClosed()) { socket = new Socket(hosts, port); // 连接socket os = socket.getOutputStream(); } Thread.sleep(100); is = socket.getInputStream(); int size = is.available(); if (size <= 0) { if ((System.currentTimeMillis() - startTime) > 3 * 10 * 1000) { // 如果超过30秒没有收到服务器发回来的信息,说明socket连接可能已经被远程服务器关闭 // socket.close(); // 这时候可以关闭socket连接 // startTime = System.currentTimeMillis(); } continue; } else { startTime = System.currentTimeMillis(); } byte[] resp = new byte[size]; is.read(resp); String response = new String(resp, "utf-8"); logger.info("连接成功:{}:{},server端返回结果:{}", hosts, port, response); } catch (Exception e) { e.printStackTrace(); try { socket.close(); is.close(); os.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } } }

最后

以上就是单薄康乃馨最近收集整理的关于Java实现socket 客户端 长连接的全部内容,更多相关Java实现socket内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(72)

评论列表共有 0 条评论

立即
投稿
返回
顶部