首页 > 其他分享 >SockerServer

SockerServer

时间:2023-09-28 17:56:23浏览次数:29  
标签:writer SockerServer println new null port clientSocket

public class SocketServer extends Thread{

private int port;

private SocketMsgListener socketMsgListener;

public static List<RfidText> rfidTextList = null;

public SocketServer(int port, SocketMsgListener socketMsgListener) {
this.port = port;
this.socketMsgListener = socketMsgListener;
}

@Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server listening on port " + port);

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

// 处理客户端发送的数据
handleClientRequest(clientSocket);
}
} catch (IOException e) {
e.printStackTrace();
}
}

private void handleClientRequest(Socket clientSocket) throws IOException {
BufferedReader bufferedReader = null;
PrintWriter writer = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
//true,表示自动刷新,不需要人为触发
writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream()), true);

String receiveData;
while ((receiveData = bufferedReader.readLine()) != null) {
if ("exit".equals(receiveData)) {
System.out.println("退出连接通信\t");
break;
}
System.out.println("接收内容:\t" + receiveData);
JSONObject jsonObject = JSONObject.parseObject(receiveData);
Integer gridNo = (Integer) jsonObject.get("data");
Integer type = (Integer) jsonObject.get("type");
SocketVo socketVo = new SocketVo();
socketVo.setData(gridNo);
socketVo.setType(type);
SocketResult socketResult = socketMsgListener.execute(socketVo);
if (SocketMsgType.INVENTORY_GRID.getValue().equals(type)) {
try {
//等待盘点
// Thread.sleep(5000);
List<RfidText> data = SocketServer.rfidTextList;
socketResult.setData(data);
SocketServer.rfidTextList = null;
writer.println(JSONObject.toJSONString(socketResult));
} catch (Exception e) {
e.printStackTrace();
}
} else {
writer.println(JSONObject.toJSONString(socketResult));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) writer.close();
if (bufferedReader != null) bufferedReader.close();
clientSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}

public interface SocketMsgListener {
SocketResult execute(SocketVo socketVo);
};
}

标签:writer,SockerServer,println,new,null,port,clientSocket
From: https://www.cnblogs.com/zhen-blog/p/17736259.html

相关文章