Java,使用套接字连接发送消息时出现问题

发布于 2024-11-07 06:11:17 字数 4590 浏览 0 评论 0原文

我的 Java 程序有问题。它在服务器和许多客户端之间有一个套接字连接。这是服务器(涉及问题的部分):

private static ArrayList<ParallelServer> clientConnected = new ArrayList<ParallelServer>();


public Server(int port) {
    this.port = port;
    if (!startServer())
        JOptionPane.showMessageDialog(new JFrame(""),
                "Error!", "ERROR!",
                JOptionPane.ERROR_MESSAGE);
}

private boolean startServer() {
    try {
        server = new ServerSocket(port);
        loadDatabase();
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return true;
}

public void runServer() {
    while (true) {
        try {
            client = server.accept();
            ParallelServer pServer = new ParallelServer(client);
            clientConnected.add(pServer);
            Thread thread = new Thread(pServer);
            thread.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


public static void sendBroadcast(String username) throws IOException {
    for(int i = 0; i < clientConnected.size(); i++)
        clientConnected.get(i).sendAnswer("@change," + username);
}

并行服务器是:

    private Socket client;
    private InputStreamReader inputstreamreader;
    private BufferedReader bufferedreader;
    private PrintWriter printwriter;

    public ParallelServer(Socket client) {
        this.client = client;
    }

    public void run() {
        try {
            inputstreamreader = new InputStreamReader(client.getInputStream());
            bufferedreader = new BufferedReader(inputstreamreader);
            printwriter = new PrintWriter(client.getOutputStream(), true);
            String lineread = "";

            while (client.isConnected()) {
                lineread = bufferedreader.readLine();
                doCommand(lineread);
            }
        } catch (UnknownHostException unhe) {
        } catch (InterruptedIOException intioe) {
        } catch (IOException ioe) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void sendAnswer(String answer) throws IOException {
        printwriter = new PrintWriter(client.getOutputStream(), true);
        printwriter.println(answer);
        printwriter.flush();
    }

这是客户端:

private String serverurl = "localhost";
private int serverport = 7777;
private PrintWriter printwriter;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private Socket server;

public Client() {
    server = null;
    try {
        server = new Socket(serverurl, serverport);
        server.setSoTimeout(5000);
    } catch (UnknownHostException unhe) {
        System.out.println("UnknownHostException: " + unhe.getMessage());
    } catch (InterruptedIOException intioe) {
        System.out.println("Timeout while attempting to establish socket connection.");
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROE!",JOptionPane.ERROR_MESSAGE);
    }
}

public String sendCommand(String command) throws IOException {
    if(server == null) {
        try {
            server = new Socket(serverurl, serverport);
            server.setSoTimeout(5000);
        } catch (UnknownHostException unhe) {
            System.out.println("UnknownHostException: " + unhe.getMessage());
        } catch (InterruptedIOException intioe) {
            System.out.println("Timeout while attempting to establish socket connection.");
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROR!",JOptionPane.ERROR_MESSAGE);
        }
    }
    if(server != null) {
        printwriter = new PrintWriter(server.getOutputStream(), true);
        printwriter.println(command);
        printwriter.flush();
        inputstreamreader = new InputStreamReader(server.getInputStream());
        bufferedreader = new BufferedReader(inputstreamreader);

        return bufferedreader.readLine();
    }
    else
        return "@serverProblem";
}

该程序是一个简单的轮流在线游戏。玩家的回合是通过队列创建的,当玩家经过他的回合时,服务器会发送一条广播消息,其中显示“现在是‘玩家 1’回合”。 (例如)。我的问题是,当客户端收到消息时,它就像添加了答案“现在轮到‘玩家 1’了。”到它将收到的下一条消息。就我而言:当玩家轮到他时,他发送“@passTurn,用户名”。 ParallelServer类从队列中轮询它,将其放在队列底部,向客户端发送“@ok”告诉它轮次已成功更改,并告诉Server类发送广播消息。然后,当同一个客户端尝试执行进一步的操作时,它会考虑“现在轮到‘玩家 1’了”。作为服务器给出的答案。相反,我希望服务器和客户端一如既往地工作,并且当广播消息发出时,客户端会收到通知而不会产生任何附带影响。 我能做些什么? 谢谢。

I have a problem with my Java program. It has a socket connection between a server and many client. Here is the server (the part which concerns the problem):

private static ArrayList<ParallelServer> clientConnected = new ArrayList<ParallelServer>();


public Server(int port) {
    this.port = port;
    if (!startServer())
        JOptionPane.showMessageDialog(new JFrame(""),
                "Error!", "ERROR!",
                JOptionPane.ERROR_MESSAGE);
}

private boolean startServer() {
    try {
        server = new ServerSocket(port);
        loadDatabase();
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return true;
}

public void runServer() {
    while (true) {
        try {
            client = server.accept();
            ParallelServer pServer = new ParallelServer(client);
            clientConnected.add(pServer);
            Thread thread = new Thread(pServer);
            thread.start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


public static void sendBroadcast(String username) throws IOException {
    for(int i = 0; i < clientConnected.size(); i++)
        clientConnected.get(i).sendAnswer("@change," + username);
}

The parallel server is:

    private Socket client;
    private InputStreamReader inputstreamreader;
    private BufferedReader bufferedreader;
    private PrintWriter printwriter;

    public ParallelServer(Socket client) {
        this.client = client;
    }

    public void run() {
        try {
            inputstreamreader = new InputStreamReader(client.getInputStream());
            bufferedreader = new BufferedReader(inputstreamreader);
            printwriter = new PrintWriter(client.getOutputStream(), true);
            String lineread = "";

            while (client.isConnected()) {
                lineread = bufferedreader.readLine();
                doCommand(lineread);
            }
        } catch (UnknownHostException unhe) {
        } catch (InterruptedIOException intioe) {
        } catch (IOException ioe) {
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void sendAnswer(String answer) throws IOException {
        printwriter = new PrintWriter(client.getOutputStream(), true);
        printwriter.println(answer);
        printwriter.flush();
    }

And here is the client:

private String serverurl = "localhost";
private int serverport = 7777;
private PrintWriter printwriter;
private InputStreamReader inputstreamreader;
private BufferedReader bufferedreader;
private Socket server;

public Client() {
    server = null;
    try {
        server = new Socket(serverurl, serverport);
        server.setSoTimeout(5000);
    } catch (UnknownHostException unhe) {
        System.out.println("UnknownHostException: " + unhe.getMessage());
    } catch (InterruptedIOException intioe) {
        System.out.println("Timeout while attempting to establish socket connection.");
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROE!",JOptionPane.ERROR_MESSAGE);
    }
}

public String sendCommand(String command) throws IOException {
    if(server == null) {
        try {
            server = new Socket(serverurl, serverport);
            server.setSoTimeout(5000);
        } catch (UnknownHostException unhe) {
            System.out.println("UnknownHostException: " + unhe.getMessage());
        } catch (InterruptedIOException intioe) {
            System.out.println("Timeout while attempting to establish socket connection.");
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(new JFrame(),"Unable to reach the server!","ERROR!",JOptionPane.ERROR_MESSAGE);
        }
    }
    if(server != null) {
        printwriter = new PrintWriter(server.getOutputStream(), true);
        printwriter.println(command);
        printwriter.flush();
        inputstreamreader = new InputStreamReader(server.getInputStream());
        bufferedreader = new BufferedReader(inputstreamreader);

        return bufferedreader.readLine();
    }
    else
        return "@serverProblem";
}

The program is a simple online game with turns. Players' turns are created with a queue and when a player passes his turn, the server send a broadcast message which say "Now it is 'Player 1' turn." (for instance). My problem is that when a client receive the message, its like it add the answer "Now it is 'Player 1' turn." to the next message it will receive. In my case: when a player passes his turn, he sends "@passTurn,username". The ParallelServer class polls it from the queue, puts it at the bottom of the queue, sends the client "@ok" to tell it that the turn has changed successfully and tells the Server class to send the broadcast message. Then, when the same client will try do do a further action, it will consider "Now it is 'Player 1' turn." as the answer the server has given to it. Instead, I would like that the server and the clients work as always and when the broadcast message is cought, the client is notified without any collateral effect.
What can I do?
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦里南柯 2024-11-14 06:11:17

您的双向消息传递机制应该如下所示:

服务器:

Wait on any client InputStream
if (broadcast) 
  broadcast_message()
else 
  process_message()

客户端:

Receiving Thread:
Wait on server broadcast

Sending Thread:
Wait on messages to be sent to server from the User Input

这应该可以解决问题:)

希望它有所帮助。干杯!

Your bi-directional message passing mechanism should look something like this:

Server:

Wait on any client InputStream
if (broadcast) 
  broadcast_message()
else 
  process_message()

Client:

Receiving Thread:
Wait on server broadcast

Sending Thread:
Wait on messages to be sent to server from the User Input

This should do the trick :)

Hope it helps. Cheers!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文