英文:
BufferedReader is just waiting for the Clients response and not reflecting the code written above in actionPerformed
问题
以下是您要翻译的内容:
我正在使用套接字编程制作一个双人游戏,我正在将移动作为数据从服务器发送到客户端,反之亦然,但当服务器端进行移动时,它仍然等待客户端的移动(直到从客户端接收到数据),并且在actionPerformed中接收数据之前所做的更改不会反映出来。
这是BufferedReader的声明:
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
这是我遇到问题的代码部分:
public void actionPerformed(ActionEvent e) {
// 一些更改,如更改按钮的颜色,添加文本等
String temp, move = "";
try {
while ((temp = br.readLine()) != null) {
move += temp;
}} catch (IOException ee) {
System.out.println("从玩家2读取移动时出错");
}
这是游戏的初始状态:
游戏初始状态
这是在进行移动后应该发生的状态(在删除了BufferedReader代码之后捕获了此状态):
应该发生的状态
这是我得到的状态(在此处可以看到按钮处于按下模式,其他更改未反映出来):
正在发生的状态
有人可以帮助我找到解决方案吗?
英文:
I'm making a 2 player game using socket programming where I'm sending the moves as data from server to client and vice versa but when a move is made on server side, it still waits for the move of client side (Until data is not received from client side) and the changes made above the line of receiving data inside actionPerformed is not getting reflected.
Here is the declaration for BufferedReader:
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
and here is the code where I'm facing problem:
public void actionPerformed(ActionEvent e) {
// some changes made like changing the color of buttons, adding texts on them, etc
String temp, move = "";
try {
while ((temp = br.readLine()) != null) {
move += temp;
}} catch (IOException ee) {
System.out.println("Error in reading the move from player 2");
}
Here is the starting state of the game:
Game Starting State
Here is the state which should occur after making a move (captured this state after removing that code of BufferedReader):
State which should occur
Here is the state which I'm getting (See here the button is seen is pressed mode and other changes are not reflecting):
State which is occuring
Can anyone help me with the solution!!!
答案1
得分: 1
你正在调用这段阻塞代码:
while ((temp = br.readLine()) != null) {
在Swing事件线程上进行调用。当你这样做时,会阻塞该线程执行其重要的操作,如绘制GUI,这将导致GUI冻结。为了防止这种情况发生,这些调用必须在后台线程中进行,以免阻塞GUI的重要事件线程。Swing有一个SwingWorker类可以实现这一点,我建议你查看并使用它。请查看Lesson: Concurrency in Swing了解详细信息。
英文:
You're calling this code which is blocking code:
while ((temp = br.readLine()) != null) {
on the Swing event thread. When you do this, you block this thread from doing its important actions such as drawing the GUI, and this will cause your GUI to freeze. To prevent this from happening, such calls must be made within a background thread so as not to block the GUI's important event thread. Swing has a SwingWorker class that facilitates this, and I suggest that you look into using it. Please check out Lesson: Concurrency in Swing for the details.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论