我正在使用UDP服务器进行多人游戏,我不明白为什么我的服务器线程在其循环的第一次迭代后自行停止。以下是启动线程的Activity的代码:
public class GameActivity extends Activity {
public ServerUDP t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_game);
t = new ServerUDP();
t.setRunning(true);
t.start();
}
@Override
protected void onPause()
{
super.onPause();
t.setRunning(false);
t.interrupt();
}
@Override
protected void onDestroy()
{
super.onDestroy();
t.setRunning(false);
t.interrupt();
}
}
这是服务器代码:
public class ServerUDP extends Thread
{
private boolean mRun;
private DatagramSocket serverSocket ;
private byte[] receiveData;
private byte[] sendData;
private int ServerPort = 9000;
ServerUDP()
{
try {
if(serverSocket == null)
{
serverSocket = new DatagramSocket(null);
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(ServerPort));
receiveData = new byte[1024];
sendData = new byte[1024];
}
} catch (SocketException e) {
e.printStackTrace();
}
}
@Override
public void run()
{
while (mRun)
{
Log.v("socket","in loop");
sendData = "test".getBytes();
InetAddress local;
try {
local = InetAddress.getByName("10.0.2.2");
Log.v("socket","Sent"+sendData);
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,local, 8088);
serverSocket.send(sendPacket);
} catch (IOException e) {
e.printStackTrace();
}
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
try {
serverSocket.receive(receivePacket);
String receiveString = new String( receivePacket.getData());
Log.v("RECEIVED",receiveString);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public void setRunning(boolean b)
{
mRun = b;
}
}
问题是我只收到一条“循环”消息。我的线程似乎在一个循环后死亡。我检查了调试模式,它仍然存在,但它没有再次通过服务器循环。
任何想法为什么?
答案 0 :(得分:0)
除了IOException
(来自RuntimeException
的未经检查的异常)之外,它可能会获得异常。尝试将run
方法中的所有内容包装在try
... catch(Exception e)
块中。
答案 1 :(得分:0)
我猜你的线程在等待服务器响应的send()
或receive()
来电时都会阻塞。