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

Java 如何构建多线程套接字服务器,java,multithreading,sockets,Java,Multithreading,Sockets,我尝试构建一个可以同时与多个客户机通信的服务器。 但是线程存在一些问题,代码也不能很好地工作。 你能告诉我螺纹部分有什么问题吗?多谢各位 公共类ServerMulti extends JFrame实现ActionListener{ private static final int PORT = 60534; private JTextField textField = new JTextField(); private static JTextArea textArea = new JTextA

我尝试构建一个可以同时与多个客户机通信的服务器。 但是线程存在一些问题,代码也不能很好地工作。 你能告诉我螺纹部分有什么问题吗?多谢各位

公共类ServerMulti extends 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
}

在这里,类处理程序应该是一个可运行的类,用于处理另一个线程上的套接字。然后while循环可以返回并接受新连接。

对于初学者,您的
while
循环应该在
socket=server.accept()之前启动。
in
out
的赋值应该在工作线程中完成。我可以告诉您违反了Swing的单线程规则,请看