一 客户端发送的步骤
发送方创建步骤:
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);
二 客户端接收方创建步骤:
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 新建一个Thread类
public class UdpClientThread extends Thread { private static final String TAG = "UdpClientThread"; //IP地址 private String mAddress; //端口 private int port; //发送内容 private byte[] msg; private Handler mHandler; DatagramSocket socketUDP; private volatile boolean stopReceiver; static String[] spReceive; static LoginReciverBean loginReciverBean; static String reciverInfo; public static IClear iClear; public UdpClientThread(Handler handler, String address, int port, byte[] msg) { this.mHandler = handler; this.mAddress = address; this.port = port; this.msg = msg; loginReciverBean = new LoginReciverBean(); } @Override public void run() { super.run(); sendSocket(); } /** * 设置 */ private void sendSocket() { try { /** 发送数据 **/ InetAddress address = InetAddress.getByName(mAddress); //1.构造数据包 DatagramPacket packet = new DatagramPacket(msg, msg.length, address, port); //2.创建数据报套接字并将其绑定到本地主机上的指定端口。 socketUDP = new DatagramSocket(30000); if (socketUDP == null) { socketUDP = new DatagramSocket(null); socketUDP.setReuseAddress(true); socketUDP.bind(new InetSocketAddress(30000)); } //3.从此套接字发送数据报包。 socketUDP.send(packet); /** 接收数据 **/ receiveMessage(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void receiveMessage() { new Thread() { public void run() { byte[] receBuf = new byte[1024]; DatagramPacket packet = new DatagramPacket(receBuf, receBuf.length); while (!stopReceiver) { try { socketUDP.receive(packet); String bytes16 = bytesToHexString(receBuf); Log.e(TAG, "接收到的byte为-- " + receBuf + " 16进制 " + bytes16); String receive = new String(packet.getData(), 9, packet.getLength() - 9, "UTF-8"); spReceive = receive.split(" "); Log.e(TAG, "收到的内容为:" + receive); setReciverBean(); } catch (IOException e) { e.printStackTrace(); Log.e(TAG, "IOException:" + e); } } socketUDP.close(); } }.start(); }
2 在主main中进行调用
UdpClientThread mThread = new UdpClientThread(mHandler, mAddress, port, sendBean.getBytes());
mThread.start();
完成
客户端调试数据使用的是wiresharek工具