我正在使用 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,它将广播其名称,直到客户端尝试使用接收线程连接到它。但是我也希望能够取消尝试连接到客户端。我添加了一个取消方法,它使 createSocket 返回 null,但是接收线程仍然在接受时被阻止。我将如何结束接收线程。