繁体   English   中英

如何编写一个可以接受多个cliSocket的ServerSocket?

[英]How to write A ServerSocket which accept multiple clicent Socket?

我正在研究Socket编程。 我已经建立了这样的服务器,它应该接受多个客户端。 在这里,我有特定数量的客户端,客户端每10秒不断发送一次味精到服务器,服务器必须对其进行处理。我遇到的问题是我无法连接多个服务器,并且单个客户端在while中连续运行程序( 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();
 }
}

服务器工作正常,但我无法编写应在while(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();
}


 }

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

就像您有一个用于ServerSocket的线程一样,您需要为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();
}

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

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();
}
}

暂无
暂无

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

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