gpt4 book ai didi

java - Java 中的服务器客户端仅在我按 Enter 键时显示消息

转载 作者:行者123 更新时间:2023-12-01 06:13:00 27 4
gpt4 key购买 nike

我有这个服务器和客户端代码。如果我从服务器向客户端发送消息,除非我先向客户端发送消息或按 Enter 键,否则它不会显示,当我尝试相反的方式时,也会出现同样的问题。我该如何解决这个问题?

服务器:

   public static void main(String[] args) throws Exception {
ServerSocket sersock = new ServerSocket(3000);
System.out.println("Server ready for chatting");
Socket sock = sersock.accept(); // reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in)); // sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true); // receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
String receiveMessage, sendMessage;

GossipServer gs = new GossipServer();
gs.initalisePieces();
gs.displayBoard(pwrite);

pwrite.println("Welcome to my Chess Game - Designed by Robbie Singh");
while (true) {
if ((receiveMessage = receiveRead.readLine()) != null) {
System.out.println(receiveMessage);
}
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
}
}

客户:

public static void main(String[] args) throws Exception {
Socket sock = new Socket("127.0.0.1", 3000); // reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in)); // sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true); // receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Welcome to my Chess Game - Designed by Robbie Singh");
String receiveMessage, sendMessage;
while (true) {
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
try{
System.out.println(receiveRead.readLine());
}catch(Exception e){}
}
}, 0, 5000);
}
}
}

最佳答案

这就是在服务器端,您在主循环中等待键盘输入。

    while (true) 
{
if ((receiveMessage = receiveRead.readLine()) != null)
{
System.out.println(receiveMessage);
}

//PUT THESE LINE IN OTHER THREAD AND SHOULD FIX THE PROBLEM
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
//////////////////////////////////////////
}

顺便说一句,我建议您阅读以下链接中的聊天应用程序示例:http://cs.lmu.edu/~ray/notes/javanetexamples/

关于java - Java 中的服务器客户端仅在我按 Enter 键时显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31213063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com