Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

java - How to build a multithreading socket server

I try to build server that could talk with several clients at the same time. But there are some problems with the thread, and the code doesn't work well. Could you tell me what is wrong with the thread part? Thank you very much.

public class ServerMulti extends JFrame implements 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()+"
");
    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 + "
");

        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+"
");
            } catch (IOException e) {
                System.out.println("Fail");
                e.printStackTrace();
            }   
        }
    }
}

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are a couple of problems with this, but in terms of multithreading the server: ServerSocket.accept() blocks until a new client attempts to connect. In your code this only happens once; so only one client will be accepted. The layout should instead be something like this:

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
}

Here the class Handler should be a Runnable class that deals with the socket on another thread. The while loop can then go back and accept a new connection.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...