安卓开发 局域网UDP获取服务器Ip地址

注:近些天做了关于“android开发UDP获取服务器ip地址”的小软件,服务器是linux系统,服务端的编码是用C语言写的,但是万变不离其宗,客户端不一定需要C语言编写,Java也照样能配对上的。

1.只需要一个button

安卓开发 局域网UDP获取服务器Ip地址_第1张图片连接好网络(wifi)此时服务器在接收状态,接受到什么都会返回ip和端口给客户端。

2.接收

try {
			mHandler.post(new myRunnable("开始UDP连接"));
			InetAddress serverAddress = InetAddress.getByName("255.255.255.255");//广泛广播地址
			byte[] bytesToSend = "test_client".getBytes();
            
			int servPort = 6000;//与服务端一致的port

			try {
				DatagramSocket socket = new DatagramSocket();
				socket.setSoTimeout(TIMEOUT);
				
				DatagramPacket sendPacket = new DatagramPacket(bytesToSend,bytesToSend.length,serverAddress,servPort);
				byte[] buf = new byte[1024];
				DatagramPacket receivePacket = new DatagramPacket(buf, buf.length);
				
				int tries = 0;
				
				boolean receivedResponse = false;
				
				do{
					socket.send(sendPacket);
					
					try{
						socket.receive(receivePacket);
						if(!receivePacket.getAddress().equals(serverAddress)){
							System.out.println("接收到了一个个未知来源的数据包");
						}
						receivedResponse = true;
					}catch(InterruptedIOException e){
						tries +=1;
						System.out.println("Time out,"+(MAXTRIES - tries)+ " more tries....");
					}
				}

安卓开发 局域网UDP获取服务器Ip地址_第2张图片

3.结果

if(receivedResponse){					
					String rcvd = "Received from " + receivePacket.getAddress() + ", Data="
                            + new String(receivePacket.getData(), 0, receivePacket.getLength());
					mHandler.post(new myRunnable(rcvd));
					//System.out.println("Received:"+new String(receivePacket.getData()));
					//mHandler.post(new myRunnable("Received:"+new String(receivePacket.getData())));
				}else{
					System.out.println("NO response -- giving up.");
					mHandler.post(new myRunnable("NO response -- giving up."));
				}
				socket.close(); 

安卓开发 局域网UDP获取服务器Ip地址_第3张图片

ps:接下来还可以进一步做下去,跟服务器正常对话!
源代码下载地址: http://download.csdn.net/detail/qq_18235445/9570071

你可能感兴趣的:(源码)