【问题标题】:How to write A ServerSocket which accept multiple clicent Socket?如何编写一个接受多个客户端 Socket 的 ServerSocket?
【发布时间】:2015-01-22 05:49:32
【问题描述】:

我正在从事 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();
 }
}

服务器工作正常,但我无法编写应该在 while(true) 循环中运行以将味精发送到服务器并允许其他客户端也连接到服务器的客户端程序。 但是对于我这样写的单个客户,

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 创建一个线程,然后它立即循环回来阻塞并等待接受另一个 Socket。
  • 你能显示一些代码 sn-p 吗? .

标签: java sockets serversocket


【解决方案1】:

就像你有一个 ServerSocket 的线程一样,你需要为 serverSocket.accept() 返回的每个 Socket 创建一个线程,然后它立即循环回来阻塞并等待接受另一个 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();
}

【讨论】:

  • 它应该在客户端套接字中吗?
  • 在我的情况下应该如何?
  • @Raghu 当你看到它时你不认识服务器端代码?即使它包含ServerSocket?你只是要求有人为你写出所有的代码吗?
【解决方案2】:

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

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

【讨论】:

  • 谢谢你,但是客户如何,我必须在我的客户中进行哪些更改
  • 客户端无需更改。您问的是如何允许多个客户端同时使用服务器?
猜你喜欢
  • 2015-05-03
  • 1970-01-01
  • 2011-04-13
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多