我是编程客户端/服务器游戏。我正在使用Eclipse。客户端是与GUI的Swing。到目前为止,我运行服务器一次,然后我运行客户端,右键单击class -> run as。一切都很好。现在我需要运行客户端类两次。当服务器和客户端运行时,我尝试过,只是再次右键单击客户端->运行为。有两个客户端进程,但只有一个GUI JFrame。
我想以这种方式测试,运行服务器,运行客户端,运行客户端,所以两个客户端正在运行,然后在第一个客户端上我想点击第一个按钮(这是新游戏),在第二个客户端上我想点击第二个按钮(它是现有的游戏连接),但对我来说,它无法为两个客户端进程运行两个GUI。我只有第一个客户端的第一个GUI,然后只运行第二个客户端的进程(没有GUI)
非常感谢,
Marek
编辑:SERVER - main
public static void main(String [] argv) throws IOException,ClassNotFoundException {
ServerListen server = new ServerListen(PORT);
server.acceptConnection();
}
SERVER - acceptConnection(); Socket dataSocket = null;
ObjectInputStream readBuffer = null;
ObjectOutputStream writeBuffer = null;
while( true ) {
try{
dataSocket = socket.accept();
System.err.println("!!! Connection !!!");
writeBuffer = new ObjectOutputStream(dataSocket.getOutputStream());
writeBuffer.flush();
readBuffer = new ObjectInputStream((dataSocket.getInputStream()));
writeBuffer.writeObject("OKlisten");
writeBuffer.flush();
System.err.println("Client connected");
new Handler(dataSocket,readBuffer,writeBuffer).runGame(list_of_games);
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
}
}
只运行一次。
CLIENT - main
public static void main(String [] argv) throws IOException, ClassNotFoundException {
Client client = new Client(PORT);
final Basic frame = new Basic(client);
frame.setVisible(true);
}
p。S -你看到的印刷!!连接! !当我做右键->运行作为客户端第二次没有第二!!连接! !消息
非常感谢
编辑2。
public Client(int PORT)
{
try{
this.clientSocket = new Socket(serverName, PORT);
sendMessage = new ObjectOutputStream(clientSocket.getOutputStream());
sendMessage.flush();
getMessage = new ObjectInputStream(clientSocket.getInputStream());
}
这是代码的一部分,在第二个客户端,它冻结在getMessage行
您需要运行任何长时间运行的代码,例如后台线程中的while (true)
循环,否则您可能会占用Swing事件线程,冻结您的应用程序。
// implement Runnable so it can be run in a background thread
public class MultiServer2 implements Runnable {
public static final int PORT_NUMBER = 2222;
private static final int THREAD_POOL_COUNT = 20;
private List<MultiClientHandler> clientList = new ArrayList<>();
private ServerSocket serverSocket;
private ExecutorService clientExecutor = Executors.newFixedThreadPool(THREAD_POOL_COUNT);
public MultiServer2() throws IOException {
serverSocket = new ServerSocket(PORT_NUMBER);
}
@Override
public void run() {
// do this in the run method so that it runs in a background thread
while (true) {
try {
Socket clientSocket = serverSocket.accept();
// MultiClient2 also implements Runnable
MultiClientHandler client = new MultiClientHandler(clientSocket);
clientList.add(client);
// and each socket's code needs to be run in its own thread
clientExecutor.execute(client);
} catch (IOException e) {
// TODO notify someone of problem!
e.printStackTrace();
}
}
}
有一个main方法,看起来像这样:
public static void main(String[] args) {
try {
MultiServer2 multiServer = new MultiServer2();
new Thread(multiServer).start(); // this runs the runnable
} catch (IOException e) {
e.printStackTrace();
}
}