一,UDP传输DatagramSocket和DatagramPacket:
示例代码:
/**
* UDP发送
* 步骤:
* 1.创建UDP服务--DatagramSocket
* 2.确定发送的数据并封装--DatagramPacket
* 3.发送数据--send
* 4.关闭资源--close
* @author 小苏
*
*/
public class Test_UDP {
public static void main(String[] args) {
DatagramSocket ds = null;
try {
// 1.创建UDP服务
ds = new DatagramSocket();
// 2.确定发送的数据并封装
byte[] buff = "hello world".getBytes();
DatagramPacket dp = new DatagramPacket(buff, buff.length,
InetAddress.getByName("localhost"), 10000);
//3.发送数据
ds.send(dp);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ds != null){
//4.关闭资源
ds.close();
}
}
}
}
/**
* UDP接收
* 1.创建UDP服务,注:接收端必须指定接收端口;
* 2.定义存储数据的数据包;
* 3.接收数据包;
* 4.解包
* 5.关闭资源
*/
class UDPRec{
public static void main(String[] args){
DatagramSocket ds = null;
try {
//1.创建UDP服务
ds = new DatagramSocket(10000);
//2.定义存储数据的数据包
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf , buf.length);
//3.接收数据包
ds.receive(p);
//4.解包
byte[] data = p.getData();
InetAddress address = p.getAddress();
///newString(data,0,p.getLength())注意转换长度
System.out.println(new String(data,0,p.getLength())+"---"+address.getHostName());
} catch (Exception e) {
e.printStackTrace();
}finally{
//4.关闭资源
if(ds != null){
ds.close();
}
}
}
}
二.UDP实现简单聊天示例代码:
示例代码:
public class Test_UDP_con {
public static void main(String[] args) {
UDPSend s = new UDPSend();
UDPRec_con r = new UDPRec_con();
Thread t1 = new Thread(s);
Thread t2 = new Thread(r);
t1.start();
t2.start();
}
}
/**
* 发送端
* @author 小苏
*
*/
class UDPSend implements Runnable{
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while(true){
String line = reader.readLine();
//设置结束标记
if(line.equals("break")){
break;
}
byte[] buff = line.getBytes();
DatagramPacket dp = new DatagramPacket(buff, buff.length,
InetAddress.getByName("localhost"), 10000);
ds.send(dp);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(ds != null){
ds.close();
}
}
}
}
/**
* 接收端
* @author 小苏
*
*/
class UDPRec_con implements Runnable{
@Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket(10000);
byte[] buf = new byte[1024];
//循环接收消息
while(true){
DatagramPacket p = new DatagramPacket(buf , buf.length);
ds.receive(p);
byte[] data = p.getData();
InetAddress address = p.getAddress();
System.out.println(new String(data,0,p.getLength())+"---"+address.getHostName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}