如何在插座上允许多个连接?
在您提出问题之前,我已经查看了相关主题,但我无法使其发挥作用。我正在使用一个帖子,但我相信我错了。这是我的代码:
感谢。
Server.java
package server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import entities.Player;
public class Server extends JFrame {
static ServerSocket serverSocket;
static Socket clientSocket;
static Socket socket;
public static int port = 43594;
static JPanel panel = new JPanel();
Player player = new Player();
public static JLabel players;
public static String s;
public void initialize() throws IOException {
serverSocket = new ServerSocket(port);
frame();
for (;;) {
Socket clientSocket = null;
clientSocket = serverSocket.accept();
new Thread(new ConnectionHandler(clientSocket)).start();
}
}
public void frame() {
JLabel status = new JLabel("Server is running on 43594");
s = String.valueOf(player.playerCount);
players = new JLabel(s);
panel.add(status);
panel.add(players);
add(panel);
setSize(400, 400);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
ConnectionHandler.java
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import entities.Player;
public class ConnectionHandler implements Runnable {
private Socket clientSocket;
Player player = new Player();
public ConnectionHandler(Socket socket) {
player.playerCount++;
Server.s = String.valueOf(player.playerCount);
Server.players.setText(Server.s);
clientSocket = socket;
}
public void run() {
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String nextline;
try {
while ((nextline = in.readLine()) != null) {
System.out.println(nextline);
}
} catch (SocketException e) {
player.playerCount--;
Server.s = String.valueOf(player.playerCount);
Server.players.setText(Server.s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端连接和断开连接工作正常,我无法一次连接多个客户端。提前谢谢。
答案 0 :(得分:-1)
"我弄清楚为什么它无法处理多个客户端。它与我制作的一些类对象和静态变量有关。虽然它已经修好了:) - "