gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:29:10 25 4
gpt4 key购买 nike

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

公共(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com