我正在使用 Java 创建一个简单的套接字服务器。我一次可以连接一个客户端,我尝试实现线程来处理多个客户端。在我的服务器构造函数中,我创建了一个处理 ServerSocket 的线程,并且应该继续监听新客户端。连接套接字后,我尝试创建另一个线程来处理客户端套接字。但我仍然无法连接多个客户端。我尝试连接的第二个客户端不会获得 IO 流。
public class Server extends JFrame {
private JTextField enterField;
private JTextArea displayArea;
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
private int counter = 1;
public Server() {
super("Server");
enterField = new JTextField();
enterField.setEditable(false);
enterField.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
sendData(event.getActionCommand());
enterField.setText("");
}
});
add(enterField, BorderLayout.NORTH);
displayArea = new JTextArea();
add(new JScrollPane(displayArea));
setSize(300, 150);
setLocation(500, 500);
setVisible(true);
new Thread(new Runnable() {
public void run() {
try {
server = new ServerSocket(50499, 100);
displayMessage("Listening on Port: "
+ server.getLocalPort() + "\n");
for (;;) {
Socket nextClient = server.accept();
displayMessage("Client Connected");
new ClientThread(nextClient).start();
nextClient = null;
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
}).start();
}
private void closeConnection() {
displayMessage("\nTerminating connection\n");
setTextFieldEditable(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
private void displayMessage(final String string) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
displayArea.append(string);
}
});
}
private void setTextFieldEditable(final boolean editable) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
enterField.setEditable(editable);
}
});
}
private void sendData(String message) {
try {
output.writeObject("SERVER>>> " + message);
output.flush();
displayMessage("\nSERVER>>> " + message);
} catch (IOException ioException) {
displayArea.append("\nError Writing Object");
}
}
private class ClientThread extends Thread {
public ClientThread(Socket socket) throws IOException {
try {
connection = socket;
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
displayMessage("Got I/O Stream\n");
displayMessage("Connection " + counter + " received from: "
+
connection.getInetAddress().getHostName());
counter++;
String message = "Connection Sucessful";
sendData(message);
setTextFieldEditable(true);
do {
message = (String) input.readObject();
displayMessage("\n" + message);
} while (!message.endsWith(">>> TERMINATE"));
} catch (ClassNotFoundException classNotFoundException) {
displayMessage("\nUnknown object type recieved");
} finally {
closeConnection();
}
}
}
}