• 安卓4.0以上 UDP 发送端


    安卓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     }
    View Code


    然而接收端的一个实例,代码从网上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 } 

    参考:http://bbs.51cto.com/thread-1084471-1.html

  • 相关阅读:
    wince 操作sqlite数据库
    c#数据结构(第二章)
    C#数据结构(第三章)
    近期学习(收藏地址)
    c#数据结构(第四章)
    PowerDesigner 数据库设计
    wince操作远程sqlserver数据库
    一个有趣的算法
    c#数据结构(第一章)
    c#实现显示图片的动态效果
  • 原文地址:https://www.cnblogs.com/SeawinLong/p/4080564.html
Copyright © 2020-2023  润新知