1.客户端:
public
class
UDPClient {
public static void main(String[] args) {
DatagramSocket socket = null;
DatagramPacket packet = null;
try {
// 1.客户端在9999端口监听
socket = new DatagramSocket(9999);
// 2.接收数据,指定接收多少
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, 1024);
// 3.接收数据并存在数据包中
socket.receive(packet);
// 4.把数据包中的数据得到
// 5.得到的数据是byte,换成string,得到是谁发送的
String data = new String(packet.getData());
int length = packet.getLength();
int port = packet.getPort();
String hostAddress = packet.getAddress().getHostAddress();
System.out.println("数据是:" + data + ";长度是:" + length + ";端口:" + port
+ ";地址:" + hostAddress);
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != socket) {
socket.close();
}
}
}
}
总结:建立UDP接收端的思路:
1.建立udp socket 服务,因为要接收数据,必须要明确一个端口号;
2.常见数据包,用于存储接收到的数据包。
3.使用socket的receive方法将接收到的数据存储到数据包中;
4.通过数据包的方法解析数据包中的数据;
5.关闭资源;
2.服务端:
public static void main(String[] args) {
// 1.UDP协议:DatagramSocket DatagramPacket
DatagramSocket socket = null;
DatagramPacket packet = null;
// 2.服务端是发送数据,准备要发送的数据
String str = "Hello World,老大来了";
try {
// 3.服务器端在8888端口监听,准备接受客户端的数据;
// 4.将数据包装成数据包,服务器往哪里发送
/**
* buf[]:将要发送的数据变成byte[]
* len:要发送的数据的长度
* InetAddress:往哪里发送
* port:往哪个端口发送
*/
packet = new DatagramPacket(str.getBytes(), str.length(),
InetAddress.getByName("localhost"), 9999);
socket = new DatagramSocket(8888);
// 5.利用socket发送;
socket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != socket) {
socket.close();
}
}
}
3050

被折叠的 条评论
为什么被折叠?



