我有服务器向每个新客户端发送当前服务器的问题。这个问题是在打开套接字并获取流之后被imidietaly发送的。
第一个客户端设法获取我发送的所有数据,这意味着:
-String" QUESTION_COMING"
- 正确的问题对象
每个下一个客户端都在客户端readLine()方法被阻止,这意味着我不是在服务器发送问题之前执行readLine()方法。当我在服务器端套接字线程上进行一些睡眠,甚至是50ms时,一切正常。
任何人都知道如何知道客户端是否已准备好阅读而不在服务器端的新套接字线程上进行休眠?
代码:
------- SERVER SIDE --------
try {
OutputStream os = socket.getOutputStream();
printWriter = new PrintWriter(os);
objectOutputStream = new ObjectOutputStream(os);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
isRunning = false;
}
printWriter.println("QUESTION_COMING");
printWriter.flush();
logger.info("Sent phrase \"QUESTION COMING\"");
try {
assert gameManager != null;
objectOutputStream.writeObject(gameManager.getCurrentQuestion());
objectOutputStream.flush();
logger.info("Sent " + gameManager.getCurrentQuestion());
} catch (IOException e) {
e.printStackTrace();
}
-------- CLIENT SIDE ---------
while(isRunning) {
try {
String line = bufferedReader.readLine();
logger.info("Got line - " + line);
proceedIncomingString(line);
} catch (IOException e) {
isRunning = false;
e.printStackTrace();
}
}
private void proceedIncomingString(String string) {
try {
if(string.equals("QUESTION_COMING")) {
Logger logger = LoggerFactory.getLogger(MySocket.class);
logger.info("Starting reading object");
Question question = (Question) objectInputStream.readObject();
logger.info("Read object: " + question);
Main.controller.setCurrentQuestion(question.getContent());
} else if(string.equals("WRONG")){
} else if(string.equals("CORRECT")) {
}
} catch(IOException | ClassNotFoundException e) {
isRunning = false;
e.printStackTrace();
}
}
日志:
------ SERVER ------
1 [pool-2-thread-2] INFO sample.ClientSocket - 启动套接字 - 套接字[addr = / 127.0.0.1,port = 51861,localport = 5000] 237
237 [pool-2-thread-2] INFO sample.ClientSocket - 发送短语"问题 COMING"
253 [pool-2-thread-2] INFO sample.ClientSocket - 已发送 题?
2264 [pool-2-thread-3] INFO sample.ClientSocket - 开始 socket - 套接字[addr = / 127.0.0.1,port = 51867,localport = 5000]
2264 [pool-2-thread-3] INFO sample.ClientSocket - 发送短语"问题 COMING"
2264 [pool-2-thread-3] INFO sample.ClientSocket - 已发送 问题
------第一位客户------
0 [Thread-5] INFO sample.MySocket - 启动套接字 - 套接字[addr = localhost / 127.0.0.1,port = 5000,localport = 51861]
238 [Thread-5] INFO sample.MySocket - 得到了行 - QUESTION_COMING 238 [Thread-5] INFO sample.MySocket - 开始阅读对象
262 [Thread-5] INFO sample.MySocket - 读取对象:问题?
------第二个客户------
0 [Thread-5] INFO sample.MySocket - 启动套接字套接字[addr = localhost / 127.0.0.1,port = 5000,localport = 51867]