我目前正在为我的大学开发一款TicTacToe多线程网络游戏,而且我遇到了一个恼人的问题。
我希望我的服务器每次接受2个连接,然后等待其他2个连接等。
问题在于,在我的代码中,如果客户端连接到服务器并在第二个客户端尚未连接到服务器时关闭连接,则第二个客户端无法播放,因为它"认为& #34;第一个客户端已连接并准备就绪。
我想做this之类的事情,但我找不到实际实现它的方法。
服务器分为3个类:
TTT_Server类:
public class TTT_Server()
{
private static ServerSocket serverSocket;
private static boolean running = true;
public static void main(String[] args)
{
try
{
// creazione ServerSocket sulla porta 8089
serverSocket = new ServerSocket(8089);
System.out.println("Server Socket creata e in ascolto sulla porta 8089");
while(running)
{
TTT ttt = new TTT();
Socket socket1 = serverSocket.accept();
Socket socket2 = serverSocket.accept();
TTT_ServerThread st1 = new TTT_ServerThread(socket1, 1, ttt, socket2);
TTT_ServerThread st2 = new TTT_ServerThread(socket2, 2, ttt, socket1);
st1.start();
st2.start();
System.out.println("thread lanciati");
}
}
catch(IOException e)
{
System.out.println(e);
running = false;
}
finally
{
try
{
serverSocket.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
}
}
(TTT_ServerThread类的一部分):
private Socket socket;
private Socket socketOtherPlayer;
private BufferedReader in;
private PrintWriter out;
private PrintWriter outOtherPlayer;
private TTT TicTacToe;
private int player;
private boolean fineGioco;
private int counter = 0;
public TTT_ServerThread(Socket socket, int num_connessione, TTT ttt, Socket socketOtherPlayer)
{
this.socket = socket;
this.socketOtherPlayer = socketOtherPlayer;
this.player = num_connessione;
this.TicTacToe = ttt;
try
{
this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.out = new PrintWriter(socket.getOutputStream());
this.outOtherPlayer= new PrintWriter(socketOtherPlayer.getOutputStream());
}
catch(IOException e)
{
System.out.println(e);
}
}
@Override
public void run()
{
//[...]
}
(TTT课程的一部分):
public class TTT
{
private int[] board = new int[9];
private int turno = 1;
public TTT()
{
for (int i = 0; i < 9; i++)
board[i] = 0;
}
protected synchronized void setBoard(int locazioneMossa, int giocatore)
{
board[locazioneMossa] = giocatore;
}
protected synchronized int getBoard(int locazioneMossa)
{
return board[locazioneMossa];
}
protected synchronized void setTurno(int turnoRicevuto)
{
turno = turnoRicevuto;
}
protected synchronized int getTurno()
{
return turno;
}
//[...]
}
有没有办法实现我想到的那种图表?
先谢谢大家的帮助!抱歉我的英语,它不是我的主要语言。
答案 0 :(得分:1)
您应该一次只接受一个连接,而不是尝试“一次接受两个连接”。如果没有等待连接,则应将连接置于等待列表中。如果是等待连接,请将它们配对。
这样你每个循环就会有一个accept()
,但有两种方法可以处理它们。