我正在使用java套接字制作多人游戏。我有这个代码
class GetServer
{
private boolean connected = false;
private Socket s = null;
public Socket createSocket(String name)
{
return createSocket(name, 55902);
}
private synchronized Socket createSocket(String serverName, int port)
{
receivingThread.start();
try
{
DatagramSocket ss = new DatagramSocket();
ss.setBroadcast(true);
byte[] b = serverName.getBytes();
DatagramPacket p = new DatagramPacket(b, b.length);
p.setAddress(InetAddress.getByAddress(new byte[] {(byte) 255, (byte) 255, (byte) 255, (byte) 255}));
p.setPort(55902);
while(!connected)
{
p.setData(b);
ss.send(p);
}
return s;
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
}
public void cancel()
{
connected = true;
}
private Thread receivingThread = new Thread(new Runnable()
{
public void run()
{
try
{
ServerSocket socket = new ServerSocket(55902);
s = socket.accept();
connected = true;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
这是服务器用于连接到客户端的类。我们的想法是使用服务器的名称调用createSocket,它将广播其名称,直到客户端尝试使用接收线程连接到它。但是我也希望能够取消尝试连接到客户端。我添加了一个cancel方法,它使createSocket返回null,但receiveThread仍然在accept上被阻止。我将如何结束接收线程。