简体   繁体   English

Java客户端服务器多线程,仅适用于一个连接

[英]java client server multithreaded, works for only one connection

I did my client-server application but at the moment only one user can use it. 我做了我的客户端服务器应用程序,但是目前只有一个用户可以使用它。 Could you help me how to make it working for more than one user. 您能帮助我如何使它为多个用户使用吗? I have the following functionality: On every two minutes counter is starting to decrease. 我具有以下功能:每两分钟,计数器开始减少。 Every user have 30 seconds to connect to the application. 每个用户都有30秒的时间连接到该应用程序。 Every connected user should see same result with which he should make some other actions. 每个连接的用户应看到相同的结果,并应采取其他措施。 I made it by this way at the moment. 我现在是通过这种方式实现的。 The code in the different cases is not so important. 在不同情况下的代码不是那么重要。 I need an advice how to make it working as a structure of the code. 我需要一个建议,使它成为代码结构。 Thanks in advance! 提前致谢!

import java.net.*;
import java.io.*;

public class MultiServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = null;
        boolean listening = true;

        try {
            serverSocket = new ServerSocket(4444);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 4444.");
            System.exit(-1);
        }

        while (listening)
        new MultiServerThread(serverSocket.accept()).start();

        serverSocket.close();
    }
}




import java.net.*;
import java.io.*;
import java.util.HashMap;

public class MultiServerThread extends Thread {
    private Socket socket = null;

    public MultiServerThread(Socket socket) {
        super("MultiServerThread");
    this.socket = socket;
    }

    public void run() {
        try {

            ObjectOutputStream toServer = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream fromServer = new ObjectInputStream(socket.getInputStream());

            int userProcess = 0;
            Object data = 11111;
            boolean listening = true;


            CountDown c = new CountDown();
            int timeRemaining = 900;

            while (listening) {
                boolean send = true;
                Object ob;
                try {
                    ob = fromServer.readObject();
                    userProcess = Integer.parseInt(ob.toString());
                    HashMap<String,Integer> finalScores = new HashMap<String,Integer>();
                    if(userProcess == 0) {
                        timeRemaining = c.getRemainingTime();
                        int temp = 999;
                        while(timeRemaining-110>0) {
                            timeRemaining = c.getRemainingTime();
                            if(temp != timeRemaining) {
                                toServer.writeObject(timeRemaining-110);
                                toServer.flush();
                                temp = timeRemaining;
                            }
                        } 
                    } 
                    if(userProcess == 0 && timeRemaining-110 < 0) {
                        c = new CountDown();
                        send = false;
                    }

                    if(userProcess == 1) {   
                        BoardGeneraor board = new BoardGeneraor();
                        data = board.getBoard();
                    } 
                    if(userProcess == 2) {   
                        int score = (Integer)fromServer.readObject();
                        String username = (String)fromServer.readObject();
                        finalScores.put(username, score);
                        data = finalScores;
                        c = new CountDown();
                    }
                    if(send) {
                       toServer.writeObject(data);
                        toServer.flush();
                    } else {
                        toServer.writeObject("quit");
                        toServer.flush();
                    }
                } catch (ClassNotFoundException e) {
                    System.out.println(e);
                }
            }

            fromServer.close();
            toServer.close();
            socket.close(); 

        } catch(IOException e) {
             System.out.println(e);
        }
    }
}

I think your problem is that you have confused the server and client and have put the client and server code within the same Java file. 我认为您的问题是您混淆了服务器和客户端,并将客户端和服务器代码放在同一Java文件中。 It looks like you intend MultiServerThread to be the client, since it interprets the socket's output stream as going "to server" and the socket's input stream as coming "from server." 看起来您打算让MultiServerThread成为客户端,因为它会将套接字的输出流解释为“到服务器”,而套接字的输入流则解释为“来自服务器”。 But when you create a MultiServerThread with serverSocket.accept() , you're giving it a socket that represents the server's side of the connection to one client. 但是,当你创建一个MultiServerThreadserverSocket.accept()你给它一个表示连接到一个客户端的服务器端的插座。 Thus the output stream returned by socket.getOutputStream() represents a stream from the server to the client . 因此,由socket.getOutputStream()返回的输出流表示从服务器到客户端的流。 What MultiServerThread should actually represent is one instance of the server talking to a client, not one instance of a client connecting to the server. MultiServerThread实际上应该代表的是与客户端通信的服务器的一个实例,而不是与服务器连接的客户端的一个实例。

In order to have clients connect to your server, you'll need a separate Java file, say Client.java, containing a separate class with a separate main method. 为了使客户端连接到服务器,您需要一个单独的Java文件,例如Client.java,其中包含一个带有单独的main方法的单独的类。 This class should open a connection to the server with the Socket(String host, int port) constructor, and treat the input stream of that socket as a stream of input from the server. 此类应使用Socket(String host, int port)构造函数打开与服务器的连接,并将该Socket(String host, int port)的输入流视为来自服务器的输入流。 Here's a simple example: 这是一个简单的例子:

public class Client {

    public static void main(String[] args) {

        Socket serverConnection = null;

        try {
            serverConnection = new Socket("localhost", 4444);
        } catch(IOException e) {
            System.err.println("Could not connect to server");
            System.exit(-1);
        }

        try {
            ObjecttInputStream fromServer = new ObjectInputStream(serverConnection.getInputStream());
            Object ob = fromServer.readObject();
        } catch(IOException e) {
            System.err.println("Error reading from server");
        }

    }

}

Once you've started your server by running the MultiServer.class file, you can start a client by running the Client.class file (in a separate window, while the server is still running). 通过运行MultiServer.class文件启动服务器后,可以通过运行Client.class文件(在服务器仍在运行的单独窗口中)来启动客户端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM