功能
UDP的简单实用
代码
package com.demo;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import org.junit.Test;
/**
*
* @author Lynn UDP协议 DatagramSocket 和DatagramPacket两个类;
* 具体流程如下:
*
*/
public class Demo06 {
@Test
public void send() {
DatagramSocket socket = null;
try {
socket = new DatagramSocket();
byte[] data = "我是要发送的内容".getBytes();
//发送数据绑定IP和端口号,每一个packet的大小不超过60k,第一个参数表示要发送的数据信息,第二个参数表示发送的地址,第三个表示发送的端口号;
DatagramPacket packet = new DatagramPacket(data,0,data.length,InetAddress.getByName("127.0.0.1"),6868);
//发送数据包;
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(socket!=null) {
socket.close();
}
}
}
@Test
public void revicer() {
//开启6868端口进行接收;
DatagramSocket socket = null ;
DatagramPacket packet;
try {
socket = new DatagramSocket(6868);
byte[] data = new byte[1024];
packet = new DatagramPacket(data,0,data.length);
//接收;
socket.receive(packet);
//这里使用String(byte[] bytes ,int offset,int length);
System.out.println(new String(packet.getData(),0,packet.getLength()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(socket!=null) {
socket.close();
}
}
}
}