如何编写一个接受多个客户端Socket的ServerSocket?

时间:2015-01-22 05:49:33

标签: java sockets serversocket

我正在开发Socket编程。我已经构建了一个应该接受多个客户端的服务器。在这里,我有特定数量的客户端,客户端每隔10秒就一直向服务器发送消息,服务器必须处理它。我遇到的问题是我无法连接多个服务器,这里一个客户端是一个连续运行的程序,而( true)因此,如果一个客户端发送请求,则另一个客户端无法连接。这是我的计划。

服务器

public class SimpleServer extends Thread {

private ServerSocket serverSocket = null;
private Socket s1 = null;

SimpleServer() {
    try {
        serverSocket = new ServerSocket(1231);
        this.start();
    } catch (IOException ex) {
        System.out.println("Exception on new ServerSocket: " + ex);
    }
}

public void run() {
    while (true) {
        try {

            System.out.println("Waiting for connect to client");
            s1 = serverSocket.accept();
            System.out.println("Connection received from " + s1.getInetAddress().getHostName());

            InputStream s1In = s1.getInputStream();
            DataInputStream dis = new DataInputStream(s1In);

            String st = dis.readUTF();
            System.out.println(st);
            s1In.close();
            dis.close();
            s1.close();
           // throw new ArithmeticException();

        } catch (IOException ex) {
            Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
        }
         catch (Exception e) {
             System.out.println("Exceptiopn: "+e);
        }

    }
}

public static void main(String args[]) throws IOException {

    new SimpleServer();
 }
}

服务器工作正常,但我无法编写运行的客户端程序,而(true)循环用于将msg发送到服务器并允许其他客户端也连接到服务器。 但对于我这样写的单个客户,

public class SimClient extends Thread {

private Socket s1 = null;

SimClient() {
    //this.start();

}

public void run() {
    int i=0;
    try {
        s1 = new Socket("localhost", 1231);
    } catch (IOException ex) {
        Logger.getLogger(SimClient.class.getName()).log(Level.SEVERE, null, ex);
    }
   // while (i<10) {
        try {
            // Open your connection to a server, at port dfg1231


            OutputStream s1out = s1.getOutputStream();
            DataOutputStream dos = new DataOutputStream(s1out);

            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             System.out.println("Enter Data from Client:");
            String s = br.readLine();
            dos.writeUTF(s);
            dos.flush();
            s1out.close();
            dos.close();
           // s1.close();
            i++;

        } catch (IOException ex) {

           //ex.printStackTrace();
            System.out.println("Exception in While: "+ex.getMessage());
        }


    //}
}

public static void main(String args[]) throws IOException {

   SimClient s= new SimClient();
   s.start();
}


 }

任何人都可以帮我编写客户端程序。这对我很有帮助。

2 个答案:

答案 0 :(得分:4)

就像你有一个ServerSocket的Thread一样,你需要为serverSocket.accept()返回的每个Socket创建一个Thread,然后它会立即循环回来阻塞并等待接受另一个Socket。创建一个名为SocketHander的类,它扩展Thread并在构造函数中接受Socket。

public class SocketHandler extends Thread {
    private Socket socket;

    public SocketHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() {
        // use the socket here
    }
}

然后回到ServerSocket处理程序......

for (;;) {
    SocketHandler socketHander = new SocketHandler(serverSocket.accept());
    socketHander.start();
}

答案 1 :(得分:1)

使用固定大小的线程池通常是个好主意,因为如果请求很高,以临时方式创建线程可能会导致服务器用完线程。

public class SimpleServer extends Thread {

private ServerSocket serverSocket = null;
private static ExecutorService executor = Executors.newFixedThreadPool(100);

SimpleServer() {
    try {
        serverSocket = new ServerSocket(1231);
        this.start();
    } catch (IOException ex) {
        System.out.println("Exception on new ServerSocket: " + ex);
    }
}

public void run() {
while (true) {
    try {

        System.out.println("Waiting for connect to client");
        final Socket s1 = serverSocket.accept();
        executor.execute(new Runnable() {

            public void run() { 
                try {
                    System.out.println("Connection received from " + s1.getInetAddress().getHostName());

                    InputStream s1In = s1.getInputStream();
                    DataInputStream dis = new DataInputStream(s1In);

                    String st = dis.readUTF();
                    System.out.println(st);
                    s1In.close();
                    dis.close();
                    s1.close();
                } catch(Exception e) {
                    System.out.println("Exceptiopn: "+e);
                }
                // throw new ArithmeticException();
            }});

         } catch (IOException ex) {
                     Logger.getLogger(SimpleServer.class.getName()).log(Level.SEVERE, null, ex);
         } catch (Exception e) {
              System.out.println("Exceptiopn: "+e);
         }

}
}

public static void main(String args[]) throws IOException {

    new SimpleServer();
}
}