java socket简单客户端
代码背景:
c++项目改造成java项目,为了最大程度减小改造成本,对于socket通信接口照着c++写了一份简版.
代码实现:
1 package com.olcom.socket;
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.net.InetSocketAddress;
7 import java.net.Socket;
8 import java.net.SocketAddress;
9 import java.nio.charset.StandardCharsets;
10 import java.util.Date;
11 import lombok.extern.slf4j.Slf4j;
12
13 /**
14 * .
15 *
16 * @ClassName: SocketClient
17 * @Auther: olcom
18 * @Date: 2019/8/29 11:29:28
19 * @Version: iom-cloud-platformV1.0
20 * @Description: socket 客户端,简单封装.
21 **/
22 @Slf4j
23 public class SocketClient {
24
25 private String ip;
26 private int port;
27 private Socket socket;
28 private DataOutputStream dataOutputStream;
29 private DataInputStream dataInputStream;
30 private Date useDate; //连接使用时间,用于判断session失效
31
32 public SocketClient(String ip, int port) {
33 this.ip = ip;
34 this.port = port;
35 useDate = new Date();
36 }
37
38 public void connect() throws Exception {
39 log.debug("Entry Method:connect()");
40 try {
41 close(); //1.主动释放连接 //2.某些服务器对指定ip有链路数限制
42
43 socket = new Socket();
44 //socket.setKeepAlive(true);
45 SocketAddress socketAddress = new InetSocketAddress(ip, port);
46 socket.connect(socketAddress, 1000); //某些服务器ping延迟高时要增加,否则会报错connect timeout
47
48 dataOutputStream = new DataOutputStream(socket.getOutputStream());
49 dataInputStream = new DataInputStream(socket.getInputStream());
50
51 updateUseDate();
52 } catch (Exception e) {
53 socket = null;
54 log.error("socket connect error ip:" + ip + ",port:" + port + ",Exception:" + e.getMessage());
55
56 throw new Exception(
57 "socket connect error ip:" + ip + ",port:" + port + ",Exception:" + e.getMessage());
58 }
59 log.debug("Exit Method:connect()");
60 }
61
62 public void write(byte[] msg, int len) throws IOException {
63 log.trace("dataOutputStream.write");
64 dataOutputStream.write(msg, 0, len);
65 log.trace("dataOutputStream.flush");
66 dataOutputStream.flush();
67 updateUseDate();
68 }
69
70 public byte[] read(int bufferSize, int timeOut) throws IOException {
71 socket.setSoTimeout(timeOut * 1000);
72 byte[] bytes = new byte[bufferSize];
73 log.trace("dataInputStream.read");
74 int len = dataInputStream.read(bytes);
75 updateUseDate();
76 log.debug("readLen:" + len);
77 byte[] tempBytes = null;
78 if (len > 0) {
79 tempBytes = new byte[len];
80 System.arraycopy(bytes, 0, tempBytes, 0, len);
81 }
82 return tempBytes;
83 }
84
85 public void close() {
86 log.debug("Entry Method:close()");
87 try {
88 if (null != dataOutputStream) {
89 dataOutputStream.close();
90 }
91 if (null != dataInputStream) {
92 dataInputStream.close();
93 }
94 if (null != socket && !socket.isClosed()) {
95 socket.close();
96 }
97 socket = null;
98 } catch (IOException e) {
99 log.error("SocketClient close Exception:" + e.getMessage());
100 }
101 log.debug("Exit Method:close()");
102 }
103
104 public boolean valid() throws Exception {
105 if (null == socket || socket.isClosed() ||
106 socket.isInputShutdown() || socket.isOutputShutdown()) {
107 if (dataInputStream != null) {
108 dataInputStream.close();
109 }
110 if (dataOutputStream != null) {
111 dataOutputStream.close();
112 }
113 if (socket != null) {
114 socket.close();
115 }
116 return false;
117 }
118 return true;
119 }
120
121 public long getTimePass() {
122 log.trace("Entry Method:getTimePass(),useDate:{}", useDate.getTime());
123 Date date = new Date();
124 log.debug("Exit Method:getTimePass(),timePass:{}", date.getTime() - useDate.getTime());
125 return (date.getTime() - useDate.getTime());
126 }
127
128 public void updateUseDate() {
129 useDate = new Date();
130 }
131
132 public static void main(String[] args) {
133
134 System.out.println("SocketClient main start");
135 try {
136 System.out.println("----------try start----------");
137 SocketClient socketClient = new SocketClient("localhost", 8080);
138 socketClient.connect();
139 String strInput = "hello server !";
140 socketClient.write(strInput.getBytes(), strInput.length());
141 byte[] recv = socketClient.read(1024, 10);
142 String strOriginal = null;
143 if (null != recv) {
144 strOriginal = new String(recv, StandardCharsets.ISO_8859_1);
145 }
146 log.info("strOriginal:" + strOriginal);
147
148 System.out.println("----------try end----------");
149 } catch (Exception e) {
150 System.out.println("catch error:" + e.getMessage());
151 e.printStackTrace();
152 }
153 System.out.println("SocketClient main end");
154 }
155
156 }
maven项目示例: example-20200525-205627
浙公网安备 33010602011771号