这是我的AndroID主要活动:
public class First extends Activity {button b;@OverrIDepublic voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.main); b = (button) findVIEwByID(R.ID.button1); b.setonClickListener(new VIEw.OnClickListener() { public voID onClick(VIEw v) { // Todo auto-generated method stub Thread t = new Thread(new Second()); t.start(); } });
这是我androID中的第二课
public class Second implements Runnable {Second(){ run();}public voID run() { // Todo auto-generated method stub try { String messageStr = "Hello AndroID!"; int server_port = 9876; DatagramSocket s = new DatagramSocket(); InetAddress local = InetAddress.getByname("127.0.0.1"); int msg_length = messageStr.length(); byte[] message = messageStr.getBytes(); DatagramPacket p = new DatagramPacket(message,msg_length,local,server_port); s.send(p); } catch (Exception e) { }}}
这是我PC上的Java代码:
public static voID main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length); serverSocket.receive(receivePacket); String sentence = new String(receivePacket.getData(),receivePacket.getLength()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); System.out.println("MESSAGE RECEIVED "+sentence+" "+IPAddress+" "+port); } }解决方法 在AndroID仿真(和AndroID设备)上,127.0.0.1表示AndroID仿真机,而不是主机PC.您可以在 10.0.2.2访问您的主机 总结
以上是内存溢出为你收集整理的java – 如何在Android中使用UDP套接字?全部内容,希望文章能够帮你解决java – 如何在Android中使用UDP套接字?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)