简体   繁体   English

如何使服务器在同一端口上接受多个套接字

[英]How to get server to accept multiple sockets on same port

I want the ServerSocket to accept 2 Sockets connecting on the same port. 我希望ServerSocket接受2个连接在同一端口上的套接字。 However, it will not print out what is being read from the BufferedReader and the sockets after being connected are still null. 但是,它不会打印出从BufferedReader中读取的内容,并且连接后的套接字仍然为空。

Here is the Serversocket code: 这是Serversocket代码:

ServerSocket serverSocket = new ServerSocket(PORT);
try {
Socket con;
int socketCounter= 0;
Socket first, second;
while (socketCounter!= 2) {
        con = serverSocket.accept();
        String input;
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        if ((input = in.readLine()) != null) {
            System.out.println(input);
            if (input.equals("first")) {
                first = con;
            } else if (input.equals("second")) {
                second = con;
            } else {
                continue;
            }
        }
        socketCounter++;
    }
} catch (Exception e) {
    e.printStackTrace();
}

Here is the "first" 这是“第一”

try {
    first = new Socket(URL, PORT);
ObjectOutputStream out = new ObjectOutputStream(first.getOutputStream());
ObjectInputStream in = new ObjectInputStream(first.getInputStream());
PrintWriter pw = new PrintWriter(new OutputStreamWriter(first.getOutputStream()));
pw.println("first");
pw.flush();
} catch(Excpetion e){
    e.printStackTrace();
}

Second is basically the same: 其次基本相同:

try {
    second = new Socket(URL, PORT);
ObjectOutputStream out = new ObjectOutputStream(second.getOutputStream());
ObjectInputStream in = new ObjectInputStream(second.getInputStream());
PrintWriter pw = new PrintWriter(new OutputStreamWriter(second.getOutputStream()));
pw.println("second");
pw.flush();
} catch(Excpetion e){
    e.printStackTrace();
}

I would preferably want to do this single threaded, however, if not, it's fine. 我最好是做这个单线程,但是,如果没有,那很好。 Can anyone help? 有人可以帮忙吗?

When you create a ServerSocket, you have to define the port that server socket it will use to listen the client requests. 创建ServerSocket时,必须定义服务器套接字用来监听客户端请求的端口。 Everytime that ServerSocket receives a request, that request will be redirect to another port defined by the ServerSocket. 每当ServerSocket收到请求时,该请求将被重定向到ServerSocket定义的另一个端口。 Normally, we instanciate a new thread and associate to it the a client work. 通常,我们实例化一个新线程并将其与客户端工作相关联。 Check this example: http://www.oracle.com/technetwork/java/socket-140484.html 检查以下示例: http : //www.oracle.com/technetwork/java/socket-140484.html

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

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