android 网络编程中,两客户端之间进行通讯时不通过服务器,也就是p2p的方式,下面给大家整理了一个通讯中常用的udpmanager工具类。
代码如下:
1 package com.example.chess; 2 import java.io.IOException; 3 import java.net.DatagramPacket; 4 import java.net.DatagramSocket; 5 import java.net.InetAddress; 6 import java.net.SocketAddress; 7 import java.util.Arrays; 8 9 10 public class udpmanager implements Runnable { 11 private DatagramSocket sock; 12 private boolean isrun=true; 13 netListenter listenter; 14 public udpmanager(int port) throws Exception{ 15 sock=new DatagramSocket(port); 16 new Thread(this).start(); 17 } 18 public void send(final String text, final String ip, final int port) 19 throws Exception { 20 new Thread() { 21 public void run() { 22 try { 23 byte[] data = text.getBytes(); 24 DatagramPacket p = new DatagramPacket(data, data.length, 25 InetAddress.getByName(ip), port); 26 sock.send(p); 27 } catch (IOException e) { 28 } 29 } 30 }.start(); 31 } 32 @Override 33 public void run() { 34 try { 35 while(isrun){ 36 DatagramPacket p = new DatagramPacket(new byte[100], 100); 37 sock.receive(p); 38 byte[] data=Arrays.copyOf(p.getData(), p.getLength()); 39 if(listenter!=null)listenter.getmag(new String(data), p.getAddress(), p.getPort()); 40 } 41 } catch (IOException e) { 42 } 43 } 44 public void close(){ 45 isrun=false; 46 sock.close(); 47 } 48 interface netListenter{ 49 public void getmag(String str,InetAddress addr,int port); 50 } 51 }