@Component
@Slf4j
public class SocketListener implements CommandLineRunner {
@Resource
private TestService testService;
@Override
public void run(String... args) throws Exception {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8081);
Socket client = null;
while (true){
client = serverSocket.accept();
new Thread(new ServerThread(client, testService)).start();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
serverSocket.close();
}
}
}
@Slf4j
@Data
public class ServerThread extends Thread {
private Socket socket ;
private String key;
InputStream inputStream;
private TestService testService;
public ServerThread(Socket socket,TestService testService){
this.socket=socket;
this.testService=testService;
}
public void run(){
try {
while (true){
inputStream=socket.getInputStream();
byte[] bytes = new byte[4096];
inputStream.read(bytes);
String string = new String(bytes, "utf-8");
testService.saveData(string);
log.info("数据转化结果:"+string.trim());
}
} catch (Exception e) {
e.printStackTrace();
}
try{
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}