我试图创建一个允许多个客户端的服务器,我可以很好地连接一个客户端,但我不能用两个。我尝试将两个客户端连接到服务器是通过在main方法中创建两个客户端对象和一个服务器。以下是服务器的代码:
public class DraughtsSever extends JFrame{
JPanel panel;
JTextArea gamesList;
ServerSocket draughtsSS;
JScrollPane scroll;
Socket s;
int i = 0;
DraughtsSever(){
panel = new JPanel();
panel.setPreferredSize(new Dimension(350,350));
gamesList = new JTextArea();
//scroll.setPreferredSize(new Dimension(350,350));
gamesList.setPreferredSize(new Dimension(300,300));
//scroll.add(GamesList);
//scroll = new JScrollPane(GamesList, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
//panel.add(scroll);
this.add(panel);
panel.add(gamesList);
this.setSize(400,400);
this.setVisible(true);
this.setTitle("Draughts Server");
panel.add(gamesList);
allowConnections();
}
public void allowConnections(){
gamesList.append("Server listening on port 50000...");
try{
while(true){
draughtsSS = new ServerSocket(50000);
//s = draughtsSS.accept();
new Thread(new TestT(draughtsSS.accept())).start();
//t.start();
}
}
catch(IOException e){
System.out.println("Error :"+e.getMessage());
}
}
class TestT implements Runnable{
Socket s;
TestT(Socket s){
this.s = s;
}
public void run(){
try{
PrintWriter out = new PrintWriter(s.getOutputStream());
Scanner in = new Scanner(s.getInputStream());
gamesList.append("\n"+s.getInetAddress().toString() +" has connected.");
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected");
out.println("hello");
System.out.println(s.getInetAddress().toString() +" has connected.");
}
catch(IOException e){
}
}
}
}
以下是客户端中用于连接服务器的方法
private void setupConnection(String serverIP, String port){
int portInt = Integer.parseInt(port);
try{
InetAddress IP = InetAddress.getByName(serverIP);
int intPort = Integer.parseInt(port);
Socket clientSocket = new Socket(IP,intPort);
JOptionPane.showMessageDialog(new JFrame(), "Successfully connected to Server");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
Scanner in = new Scanner(clientSocket.getInputStream());
//in.
}
catch(Exception e){
System.out.println("ErrorC :" +e.getMessage());
}
}
} }
答案 0 :(得分:2)
我认为你应该只创建一次服务器套接字,所以将它移到while循环之外:
draughtsSS = new ServerSocket(50000);
您不需要继续重新创建它,因为当客户端连接时,它们会在您调用时自动移动到其他套接字
draughtsSS.accept()