近期接触到java socket编程,遂总结一波,方便大家一起学习取用:
一、Socket 服务端,如代码所示
/**
- 启动监听,使用 spring 框架,可以将服务端代码放入各种监听器中,伴随服务启动
-
- @throws IOException
*/
public void listen() throws IOException {
threadPoolExecutor = ThreadPoolExecutorUtil.getInstance();
//初始化Socket服务
serverSocket = new ServerSocket(payPort);
//无限阻塞监听,等待客户端接入
while (!serverSocket.isClosed()) {
//开始阻塞监听
Socket socket = serverSocket.accept();
//TODO 设置客户端与服务端进行连接的超时时间,这个在联调时可以用,上线需要去掉,影响TCP响应时间; 使用TCP/UDP 测试工具的时候,可以延长时间
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//设置读取数据时阻塞链路的超时时间,而并非连接的超时时间
socket.setSoTimeout(10000);
try {
threadPoolExecutor.execute(doSomeThing());
} catch (Exception e) {
logger.error("payServer.listen(),deal connection error", e.getMessage());
}
}
}
二、Socket 客户端端,如代码所示
public static String clientSocket(String content, String ip, Integer port, int timeout) {
String data = "";
Socket socket = null;
InputStream is = null;
OutputStream os = null;
try {
//建立连接
socket = new Socket(ip, port);
socket.setSoTimeout(timeout);
os = socket.getOutputStream();
is = socket.getInputStream();
//写请求
os.write(content.getBytes(EN_CODE));
os.flush();
//读响应
byte[] bs = new byte[39];
for (int i = 0; i < 39; i++) {
bs[i] = (byte) is.read();
}
byte[] dataBytes = new byte[bs.length];
for (int i = 0; i < bs.length; i++) {
dataBytes[i] = (byte) is.read();
}
data = new String(dataBytes, EN_CODE);
System.out.println(data);
} catch (Exception e) {
} finally {
//最后,关闭连接
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return data;
}
|