安卓4.0以上,udp套接字代码,必须有一个专门的线程来执行udp的代码:
1 private void udpSendout(MyPositionTempDataBase myPosition){ 2 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 3 strToSend = String.format("%.2f%.2f%s%s", myPosition.getX(),myPosition.getY(),myPosition.getUserHashCode(),format.format(new Date(myPosition.getPositionTime()))); 4 new Thread(){ 5 6 @Override 7 public void run() { 8 try { 9 socket = new DatagramSocket(); 10 byte buf[] =strToSend.getBytes(); 11 packet = new DatagramPacket(buf, buf.length, 12 InetAddress.getByName(remoteIP),remotePort); 13 socket.send(packet); 14 } catch (Exception e) { 15 e.printStackTrace(); 16 } 17 } 18 19 }.start(); 20 21 }
然而接收端的一个实例,代码从网上copy的:
1 public class UdpServer { 2 3 public static void main(String[] args) throws Exception { 4 5 DatagramSocket ds=new DatagramSocket(12345); 6 7 //这里定义了一个端口号12345,给客户端访问的时候使用 8 9 byte[] buf=new byte[1024]; 10 11 //定义一个字节数组供 接收客户端传输过来的数据 12 13 DatagramPacket dp=new DatagramPacket(buf, buf.length); 14 15 //定义 接收的包 你接收 用户发送过来的包 那么肯定 要有个东西去存放 它吧 16 17 ds.receive(dp); 18 19 //接收 20 System.out.println(new String(dp.getData(),0,dp.getLength())); 21 22 //接收过来的是byte数组, 你也可以利用new String 得到传输过来的字符串, dp.getLength()是 得到传输过来的字节数组的有效长度 23 24 //什么叫有效长度,就是 0值的 都不算 25 26 27 28 ds.close(); 29 30 //关闭连接 31 32 } 33 34 }