背景:我正在编写一个简单的UDP应用程序来ping我测试服务器,我每隔一分钟左右就会告诉我它仍然正常运行(我无法在服务器上为那些想知道的人启用ping).我计划在手机上运行此功能,以便在服务器不再响应时发出警告.
我正在尝试使用看似简单的java.net.DatagramSocket:
try
{
socket = new DatagramSocket();
socket.bind(null);
}
catch (SocketException e)
{
System.out.println(e.toString());
throw e;
}
Run Code Online (Sandbox Code Playgroud)
我还说我已经通过android清单启用了Internet权限,如果我删除uses子句这样做,我会收到权限错误,所以我确信它工作正常.当我将此代码下载到Android虚拟设备(AVD)并执行它时,在调用bind()时,我遇到了以下异常:
03-17 19:07:39.401:INFO/System.out(338):java.net.BindException:参数无效
根据此文档,null参数是正确的:
public void bind(SocketAddress localAddr)
自:API级别1
将此套接字绑定到localAddr指定的本地地址和端口.如果此值为null,则使用有效本地地址上的任何空闲端口.
但不信任文档,我决定在我的设备上枚举IP地址,如下所示:
ArrayList<NetworkInterface> allInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
NetworkInterface eth = allInterfaces.get(0);
InetSocketAddress addr = new InetSocketAddress(eth.getInetAddresses().nextElement(), port);
try
{
socket = new DatagramSocket();
socket.bind(addr);
}
catch (SocketException e)
{
System.out.println(e.toString());
throw e;
}
Run Code Online (Sandbox Code Playgroud)
当我单步执行代码时,它工作得很好,我可以看到AVD上的两个IP地址,但我在bind()调用上得到完全相同的异常.有没有人看到我可能会失踪的?我将继续研究并希望为我自己的问题发布一个解决方案,但我希望有人能够为我提供快捷方式.
我目前正在探索Java中的UDP数据包传输,以在Android上创建多人游戏.我成功地通过使用通常的"127.0.0.1"在我的Nexus 4中交换数据包,并且我也成功地在我的本地网络中的PC服务器和我的Android客户端之间交换数据包.但由于我希望我的游戏可以在互联网上播放,我希望我的Android客户端能够在不在同一本地网络上时与我的PC服务器交换数据包.这是我在努力的地方.
我的设置:连接家庭互联网连接的PC服务器和连接3G网络的Nexus 4.
首先,我的PC服务器开始侦听端口10000,我的Android客户端打开一个套接字,以便在端口10001上接收服务器的数据包.然后,Android客户端将一个数据包发送到PC服务器,并将其发送到端口上的当前公共地址"173.246.12.125" 10000.PC服务器接收数据包并在端口10001上向发送方发送响应.但Android客户端从不接收响应.
这是我的PC服务器代码:
public class UDPServer {
private final static int SERVER_PORT = 10000;
private final static int CLIENT_PORT = 10001;
public static void main(String[] args) {
InetAddress clientAddr = null;
DatagramSocket socket = null;
try {
//Initializing the UDP server
System.out.println(String.format("Connecting on %s...", SERVER_PORT));
socket = new DatagramSocket(SERVER_PORT);
System.out.println("Connected.");
System.out.println("====================");
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
while(true){
try {
//Listening
byte[] buf = new byte[1024];
DatagramPacket packet = …Run Code Online (Sandbox Code Playgroud)