java - 如何构建多线程套接字服务器

标签 java multithreading sockets

我尝试构建可以同时与多个客户端通信的服务器。 但线程存在一些问题,代码不能很好地运行。 你能告诉我线程部分有什么问题吗?非常感谢。

公共(public)类 ServerMulti 扩展 JFrame 实现 ActionListener{

private static final int PORT = 60534;
private JTextField textField = new JTextField();
private static JTextArea textArea = new JTextArea();    
private JButton button = new JButton();
public static ServerSocket server;
public static Socket socket;
public static BufferedReader in;
public static PrintWriter out;



public ServerMulti(){

    /*
     * build up GUI
     */
    setTitle("Server Multi");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(300,400);
    setBackground(Color.white);
    setLayout(new BorderLayout());
    button.setText("Send");
    button.setSize(300, 50);
    textField.setText("Type here");
    textArea.setSize(300, 50);
    add(textField, BorderLayout.NORTH);
    add(new JScrollPane(textArea), BorderLayout.CENTER);
    add(button, BorderLayout.SOUTH);
    setLocation(300, 100);
    button.addActionListener(this);
    setVisible(true);
}

/*
 * print out the information that need to sent to clients
 * 
 */
public void actionPerformed(ActionEvent e) {
    textArea.append(textField.getText()+"\n");
    out.println(textField.getText());
    textField.setText("");
}


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

    new ServerMulti();

    //build up the socket and server
    try{
        server = new ServerSocket(PORT);
        socket = server.accept();
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream());
        textArea.append("Connected. "+" Port: " + PORT + "\n");

        while(true){
            worker w = new worker();
            Thread t = new Thread(w);
            t.start();  
        }
    }catch (IOException e) {
        System.out.println("Accept failed:" +PORT);
        System.exit(-1);
    }
}

//to the same server, different sockets are created connecting to different client

    public static class worker implements Runnable{


    public void run() {

        String msg;

        /*
         * the "in.readLine()"  give the data only once
         * 1. so we save the information to a String from the socket
         * 2. Then sent out a feedback to client, through socket
         * 3. print out the String we just collected 
         */

        while(true){

            try {
                msg = in.readLine();
                out.println("Server received : " + msg);
                textArea.append(msg+"\n");
            } catch (IOException e) {
                System.out.println("Fail");
                e.printStackTrace();
            }   
        }
    }
}

}

最佳答案

这有几个问题,但就服务器的多线程而言: ServerSocket.accept() 会阻塞,直到新客户端尝试连接为止。在您的代码中,这只发生一次;因此只接受一名客户。布局应该是这样的:

ServerSocket ss = new ServerSocket(PORT);
while (LISTENING) {
    Socket sock = ss.accept();
    Handler handler = new Handler(sock);
    new Thread(handler).start();
    //With the LISTENING variable dealt with as well
}

这里的 Handler 类应该是一个 Runnable 类,它处理另一个线程上的套接字。然后 while 循环可以返回并接受新连接。

关于java - 如何构建多线程套接字服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20229553/

相关文章:

c# - 内存锁以确保共享数据可以被多个线程读取,但只能由一个线程写入?

C++ - websocket 客户端 n 服务器

android - 移植:Android/Linux 客户端/服务器套接字通信问题

java - 多个完整的 HTTP 请求卡在 TCP CLOSE_WAIT 状态

java - 用于大型游戏的 Java 任务编辑器

iOS Swift - 关于蓝牙低功耗管理器中的信号量和排序的问题

java - 升级到 1.1.3 spring 集成 java dsl 后,错误消息从未传递到错误 channel

java - Java中有自调优线程池吗?

java - XPath 查询返回重复节点

java - 文件名中的空格阻止下载