Android中Socket基于UDP传输

接收方创建步骤:

1.  创建一个DatagramSocket对象,并指定监听的端口号

DatagramSocket socket = new  DatagramSocket (4567);

2. 创建一个byte数组用于接收

byte data[] = new byte[1024];

3. 创建一个空的DatagramPackage对象

 DatagramPackage package = new DatagramPackage(data , data.length);

4. 使用receive方法接收发送方所发送的数据,同时这也是一个阻塞的方法

socket.receive(package); 

5. 得到发送过来的数据

new String(package.getData() , package.getOffset() , package.getLength());

 

发送方创建步骤:

1.  创建一个DatagramSocket对象

DatagramSocket socket = new  DatagramSocket (4567);

2.  创建一个 InetAddress , 相当于是地址

InetAddress serverAddress = InetAddress.getByName("想要发送到的那个IP地址"); 

3.  这是随意发送一个数据

String str = "hello";

4.  转为byte类型

byte data[] = str.getBytes();

  5.  创建一个DatagramPacket 对象,并指定要讲这个数据包发送到网络当中的哪个地址,以及端口号

DatagramPacket  package = new DatagramPacket (data , data.length , serverAddress , 4567);

6.  调用DatagramSocket对象的send方法 发送数据

 socket . send(package);

 http://www.cnblogs.com/lee0oo0/archive/2012/04/04/2431907.html
 

一、有的手机不能直接接收UDP包,可能是手机厂商在定制Rom的时候把这个功能给关掉了。

1、可先在oncreate()方法里面实例化一个WifiManager.MulticastLock 对象lock;具体如下:

WifiManager manager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
WifiManager.MulticastLock lock= manager.createMulticastLock("test wifi");

2、在调用广播发送、接收报文之前先调用lock.acquire()方法;

3、用完之后及时调用lock.release()释放资源,否决多次调用lock.acquire()方法,程序可能会崩,详情请见

Caused by: java.lang.UnsupportedOperationException: Exceeded maximum number of wifi locks

注;记得在配置文件里面添加如下权限:

<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />

经过这样处理后,多数手机都能正常发送接收到广播报文。

本小点转载自Android手机接收不到UDP报文

二、在UDP通信中,android端发送UDP广播包没有问题。至于接收的话,有时候不能接收到包。

在UDP通信中,Android端发送UDP广播包没有问题。至于接收的话,有时候不能接收到包。但是如果UDP包中指定了目标主机的地址的话,那么android端就能正常接收。

下面上一段代码,大家可用这段代码进行测试

1、在一个Service里面,我们创建一个线程

复制代码
public void onCreate() {//用于创建线程
        WifiManager manager = (WifiManager) this
                .getSystemService(Context.WIFI_SERVICE);
        udphelper = new UdpHelper(manager);
        
        //传递WifiManager对象,以便在UDPHelper类里面使用MulticastLock
        udphelper.addObserver(MsgReceiveService.this);
        tReceived = new Thread(udphelper);
        tReceived.start();
        super.onCreate();
    }
复制代码

2、弄一个UDP帮助类,这个类主要用于发送和接收数据

复制代码
package com.example.com.ihome.bang.util;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Observable;
import com.example.com.ihome.bang.tool.SendThread;
import android.net.wifi.WifiManager;
import android.util.Log;

/**
 * 
 * UdpHelper帮助类
 * 
 * @author 陈喆榕
 * 
 */
public class UdpHelper  implements Runnable {
    public    Boolean IsThreadDisable = false;//指示监听线程是否终止
    private static WifiManager.MulticastLock lock;
    InetAddress mInetAddress;
    public UdpHelper(WifiManager manager) {
         this.lock= manager.createMulticastLock("UDPwifi"); 
    }
    public void StartListen()  {
        // UDP服务器监听的端口
        Integer port = 8903;
        // 接收的字节大小,客户端发送的数据不能超过这个大小
        byte[] message = new byte[100];
        try {
            // 建立Socket连接
            DatagramSocket datagramSocket = new DatagramSocket(port);
            datagramSocket.setBroadcast(true);
            DatagramPacket datagramPacket = new DatagramPacket(message,
                    message.length);
            try {
                while (!IsThreadDisable) {
                    // 准备接收数据
                    Log.d("UDP Demo", "准备接受");
                     this.lock.acquire();
                     
                    datagramSocket.receive(datagramPacket);
                    String strMsg=new String(datagramPacket.getData()).trim();
                    Log.d("UDP Demo", datagramPacket.getAddress()
                            .getHostAddress().toString()
                            + ":" +strMsg );this.lock.release();
                }
            } catch (IOException e) {//IOException
                e.printStackTrace();
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }

    }
    public static void send(String message) {
        message = (message == null ? "Hello IdeasAndroid!" : message);
        int server_port = 8904;
        Log.d("UDP Demo", "UDP发送数据:"+message);
        DatagramSocket s = null;
        try {
            s = new DatagramSocket();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        InetAddress local = null;
        try {
            local = InetAddress.getByName("255.255.255.255");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        int msg_length = message.length();
        byte[] messageByte = message.getBytes();
        DatagramPacket p = new DatagramPacket(messageByte, msg_length, local,
                server_port);
        try {

            s.send(p);
            s.close();
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
            StartListen();
    }
}
复制代码

最后, 添加个人的实例 :

复制代码
package com.example.android.helloactivity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.example.andriod.udp.UDPClient;
import com.example.andriod.udp.UDPServer;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainAct extends Activity {
    EditText msg_et = null;
    Button send_bt = null;
    TextView info_tv = null;
    private static final String TAG ="MainAct";
    private UDPClient client;
    private String sendInfo;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.udp_test);
        msg_et = (EditText) findViewById(R.id.edit_msg);
        send_bt = (Button) findViewById(R.id.send_bt);
        info_tv = (TextView) findViewById(R.id.receive_msg);
        info_tv.setText("source");
        // 开启服务器
        ExecutorService exec = Executors.newCachedThreadPool();
        UDPServer server = new UDPServer();
        exec.execute(server);
        // 发送消息
        send_bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                myThread1 thread = new myThread1("22");
                new Thread(thread).start();

            }
        });
    }

    final Handler mHander = new Handler() {

        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            //super.handleMessage(msg);
            info_tv.setText(sendInfo);
            
            Log.d(TAG, "client.send()=");
        }
    };

    class myThread1 implements Runnable {

        private String threadName;

        public myThread1(String name) {
            this.threadName = name;
        }

        public void run() {
            Log.d(TAG, "MyThread  execu"+msg_et.getText().toString());
            client = new UDPClient(msg_et.getText().toString());
            sendInfo=client.send();
            
            Message msg = mHander.obtainMessage();
            msg.arg1=1;
            mHander.sendMessage(msg);
            Log.d(TAG, "client.send()=");
        }
    }
}
复制代码
复制代码
package com.example.andriod.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import android.util.Log;

public class UDPServer implements Runnable {
    private static final int PORT = 6000;
    private byte[] msg = new byte[2048];
    private boolean life = true;

    public UDPServer() {
    }

    public boolean isLife() {
        return life;
    }

    public void setLife(boolean life) {
        this.life = life;
    }

    @Override
    public void run() {
        DatagramSocket dSocket = null;
        DatagramPacket dPacket = new DatagramPacket(msg, msg.length);
        try {
            dSocket = new DatagramSocket(PORT);
            while (life) {
                try {
                    dSocket.receive(dPacket);
                    Log.d("tian msg sever received",
                            new String(dPacket.getData(), dPacket.getOffset(),
                                    dPacket.getLength())
                                    + "dPacket.getLength()="
                                    + dPacket.getLength());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
}
复制代码
复制代码
package com.example.andriod.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import android.util.Log;

public class UDPClient {
    private static final int SERVER_PORT = 6000;
    private DatagramSocket dSocket = null;
    private String msg;

    public UDPClient(String msg) {
        super();
        this.msg = msg;
    }

    public String send() {
        StringBuilder sb = new StringBuilder();
        InetAddress local = null;
        try {
            local = InetAddress.getByName("localhost"); // 本机测试
            sb.append("已找到服务器,连接中...").append("/n");
        } catch (UnknownHostException e) {
            sb.append("未找到服务器.").append("/n");
            e.printStackTrace();
        }
        try {
            dSocket = new DatagramSocket(); // 注意此处要先在配置文件里设置权限,否则会抛权限不足的异常
            sb.append("正在连接服务器...").append("/n");
        } catch (SocketException e) {
            e.printStackTrace();
            sb.append("服务器连接失败.").append("/n");
        }
        int msg_len = msg == null ? 0 : msg.length();
        DatagramPacket dPacket = new DatagramPacket(msg.getBytes(), msg_len,
                local, SERVER_PORT);
        try {
            dSocket.send(dPacket);
            Log.d("tian", "msg=="+msg+"dpackage="+dPacket.getData()+"dPacket.leng="+dPacket.getLength());
            sb.append("消息发送成功!").append("/n");
        } catch (IOException e) {
            e.printStackTrace();
            sb.append("消息发送失败.").append("/n");
        }
        dSocket.close();
        return sb.toString();
    }
}
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值