我正在创建一个顶级王牌的游戏,在其中我创建了一个服务器和两个客户端。我有一个控制器类,我想用来控制游戏。当我运行控制器时,它会创建我的服务器,但我必须单独运行客户端来创建它们。
有没有办法在我运行控制器时启动我的客户端以及我的服务器?我是Java的客户端/服务器的初学者,所以任何帮助都会很棒。
public static void main(String[] args) throws ClassNotFoundException, IOException {
//Empty card arrays for now while testing
Cards[] Player1 = new Cards[2];
Cards[] Player2 = new Cards[2];
Server server = new Server();
Client client = new Client(Player1, "Gary");
Client client2 = new Client(Player2, "Jack");
}
}
public class Server {
public Server() throws IOException, ClassNotFoundException{
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(3000);
System.out.println("Connecting....");
while(!serverSocket.isClosed()) {
Socket socket = serverSocket.accept();
System.out.println("Connected");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//Reads my card object
Cards card = (Cards)ois.readObject();
JFrame frame = new JFrame();
frame.setSize(600, 600);
//Test
JLabel imageLabel = new JLabel(card.image);
frame.add(imageLabel);
frame.setVisible(true);
System.out.println(card.name);
ois.close();
socket.close();
}
}
}
public class Client implements Serializable{
public Client(Cards[] hand, String string) throws IOException, ClassNotFoundException {
Socket socket = new Socket("localhost", 3000);
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//This is a test to show my card object can be passed over the stream
Cards card = new Cards(string, 9, 5, 3, 5,new ImageIcon("C:\\Users\\gary.kelly\\Pictures\\Cards\\John Snow.jpg"));
oos.writeObject(card);
oos.close();
socket.close();
}
}
答案 0 :(得分:0)
您的程序现在是单线程的,服务器接受方法阻塞主线程,因此客户端无法连接。您可以在不同的线程中启动服务器和客户端,以便在一个Java进程中一起运行它们。
new Thread(() -> new Server()).start();
new Thread(() -> new Client(Player1, "Gary")).start();
new Thread(() -> new Client(Player2, "Jack")).start();