我在两个安卓设备之间有一个网络,一个设备只会发送一个块的位置,然后连接到手机的客户端将使用这些位置来显示块,主机可以移动块,客户端可以看到这个,但是在随机的时间后,连接就会断开,但我不确定它是连接还是 doInBackground 方法。
这是引起我问题的方法
@Override
protected Object doInBackground(Object... params)
{
setUpClient();
if( host == true ) { server.execute(); }
rdyForPlay = true;
boolean run = true;
while( run )
{
//Tell the server to give position of players
if( host == false)
{
Log.d(TAG, "Running client doInBackgroundMethod");
try {
if(socket == null)
{
socket = new DatagramSocket( port );
}
byte[] bufer = new byte[256];
String msg = "position";
int msgLength = msg.length();
bufer = msg.getBytes();
InetAddress address;
address = InetAddress.getByName("192.168.1.59");
DatagramPacket p = new DatagramPacket( bufer, bufer.length , address, port );
socket.send( p );
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket( buf, buf.length );
try
{
socket.receive( packet );
}
catch (IOException e)
{
Log.d(TAG, "Error with receiving data");
e.printStackTrace();
}
String data = new String( buf, 0, packet.getLength() );
Log.d(TAG, "Data received is in run method:" + data);
//Take the data from the server and use it
String[] pos = data.split(":");
assets.get(0).setPosition( Integer.parseInt( pos[0] ), Integer.parseInt( pos[1] ) );
//ID = Integer.parseInt( data );
}
}
return null;
}
如果需要,可以提供更多代码。
帆布