如何创建多个服务器,每个服务器监听不同的端口?

hjzp0vay  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(315)

我是新的网络编程,并试图编写代码,可以创建多个不同的端口上的服务器套接字。我正在为每个服务器创建一个单独的线程。服务器本身是多线程的,因此它可以处理多个客户机。下面描述的servers.java文件调用multiechoserver.java中定义的多线程服务器类

//Server.java
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.*;

public class Servers{
    public static int ports [] = {1234, 1235, 1236, 1237, 1238};

    String s = "server_";

    public static void main(String args[]){
       for(int i = 0; i <ports.length; i++){
            String s = "server_" + Integer.toString(i);
            MyRunnable serv = new MyRunnable(s, ports[i]);
            serv.start();
        //System.out.println("Server started " + s);
        }
    }

 }

class MyRunnable extends Thread{
 public static String s;
 public static int port;
 public MyRunnable(String s, int port){
    this.s = s;
    this.port = port;
}
public void run(){
    try{

        MultiEchoServer server = new MultiEchoServer(s, port);
        server.createServer();
        //server.start();
        System.out.println("HERE");

    }
    catch(Exception e){
        e.printStackTrace();
    }
}

}

multiechoserver.java文件

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

public class MultiEchoServer{
    private static ServerSocket serverSocket;
    private static String s; 
    private static int PORT;

public MultiEchoServer(String s, int port){
    this.s = s;
    this.PORT = port;
}

public void createServer(){
    try{
        serverSocket = new ServerSocket(PORT);
        System.out.println(s);
        System.out.println("Listening at port: " + PORT);
    }
    catch(IOException ioEx){
        System.out.println("\nUnable to set up port!");
        System.exit(1);
    }

    try{
    do{

            Socket client = serverSocket.accept();
            System.out.println("\nNew client accepted.\n");
            ClientHandler handler = new ClientHandler(client);

            handler.start();
        }while(true); 
    }
    catch(IOException ioEx){
        ioEx.printStackTrace();
    }

    }
}

class ClientHandler extends Thread{
 private Socket client;
 private Scanner input;
 private PrintWriter output;

 public ClientHandler(Socket socket){
    client = socket;

    try{
        input = new Scanner(client.getInputStream());
        output = new PrintWriter(client.getOutputStream(), true);
    }
    catch(IOException ioEx){
        ioEx.printStackTrace();
    }
}

public void run(){
    String received;

    do{
        received = input.nextLine();

        output.println("ECHO: " + received);

    }while(!received.equals("QUIT"));

    try{
        if(client != null){
            System.out.println("Closing down connection");
            client.close();
        }
    }
    catch(IOException ioEx){
        System.out.println("Unable to disconnect");
    }
}

}
当我初始化一个服务器示例时,代码可以工作。但是,当一个完整的端口号数组被传递时,只有监听最后一个端口的服务器被初始化,而对于其他端口,我得到“无法设置”消息。所有端口号都有效。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题