网络编程--UDP套接字的使用举例
发送端:
package com.bjsxt.net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;
public class UDPSend {
public static void main(String[] args) {
DatagramSocket ds =null;
Scanner scan = new Scanner(System.in);
try {
//1.创建套接字
ds = new DatagramSocket();
//2.准备数据
byte[] buf = new byte[1024];
String line = null;
while((line =scan.nextLine())!=null){
buf =line.getBytes();
//3.定义数据报包
DatagramPacket dp = new DatagramPacket(buf, buf.length,
InetAddress.getByName("127.0.0.1"), 8888);
//4.发送数据
ds.send(dp);
if(line.equals("over")){
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
ds.close();
}
}
}
接收端:
package com.bjsxt.net.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
public class UDPReceive {
public static void main(String[] args) {
// 创建UDP socket
DatagramSocket ds = null;
try {
ds = new DatagramSocket(8888);
//2.定义缓冲区,用于存数据
byte[] buf = new byte[1024];
//3.定义数据报包
DatagramPacket dp = new DatagramPacket(buf, buf.length);
while(true){
//4.接受数据
ds.receive(dp);
//5.解析包中信息
String hostName = dp.getAddress().getHostAddress();
int port = dp.getPort();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println("hostName"+hostName
+"port"+port+"data:"+data);
if(data.equals("over")){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(ds!=null){
ds.close();
}
}
}
}