创建socket服务
package com.z.socket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Component
@Slf4j
public class ServerSocketConfig {
public static ServerSocket serverSocket = null;
private static final ThreadPoolExecutor threadpool = new ThreadPoolExecutor(15, 15,
10L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
@Bean
public void socketCreate() {
// 使用多线程创建,accept() 会阻塞程序执行(后面代码不能被执行)
Runnable socketRun = new Thread() {
@Override
public void run() {
log.info("创建socket线程");
try {
serverSocket = new ServerSocket(514);
log.info("socket服务端开启");
while (true) {
Socket socket = serverSocket.accept();
log.info("接收到客户端socket" + socket.getRemoteSocketAddress());
threadpool.execute(new ServerReceiveThread(socket));
}
} catch (IOException e) {
log.info("socket服务启动异常");
e.printStackTrace();
}
}
};
new Thread(socketRun).start();
}
}
监听数据
package com.z.config.socket;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
@Slf4j
public class ServerReceiveThread implements Runnable {
private Socket socket;
public ServerReceiveThread(Socket socket) {
this.socket = socket;
}
/**
* 解析为十六进制数据
*/
private String getCode(byte[] req) {
String HEXES = "0123456789ABCDEF";
final StringBuilder hex = new StringBuilder(2 * req.length);
for (int i = 0; i < req.length; i++) {
byte b = req[i];
hex.append(HEXES.charAt((b & 0xF0) >> 4))
.append(HEXES.charAt((b & 0x0F))).append(" ");
}
return hex.toString();
}
@Override
public void run() {
try {
// 接收客户端信息
InputStream inputStream = socket.getInputStream();
// 发送客户端信息
OutputStream outputStream = socket.getOutputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
byte[] b = new byte[1024];
int len = 0;
while ((len = inputStream.read(b)) != -1) {
dout.write(b, 0, len);
}
String data = getCode(out.toByteArray());
log.info("服务器收到消息:{}", data);
log.info("服务器解析消息: {}", out.toString());
String msg = "server response success";
outputStream.write(msg.getBytes());
# 关闭流
dout.close();
out.close();
inputStream.close();
outputStream.close();
socket.close();
} catch (Exception e) {
log.info("接收数据异常socket关闭");
e.printStackTrace();
} finally {
log.info("数据异常数据要怎么保留");
}
}
}
标签:info,通讯,java,log,new,import,socket
From: https://www.cnblogs.com/2393920029-qq/p/17243015.html