5.15基于UDP协议的文件传输

一、基于UDP协议的通信是不可靠的他是面向非连接的,所以传输速度较TCP快

UDP协议两个最重要的关键字为:

datagramsocketdatagrampacket

datagrampacket是用来打包数据的,将接收方的IP地址和接口都写进包内

datagramsocket负责寄出和接收这个包裹,它自己会传输到指定端口,在接受之后定义一个类型拆包

接收方可通过传送过来的包裹获取其中的socketAddress

并通过这个地址信息返回信息给寄出方


public static void main(String[] args) {
try {
String info="我是谁!";
byte[] bytes=info.getBytes();
InetAddress ia=InetAddress.getByName("localhost");
DatagramPacket packet=new DatagramPacket(bytes, bytes.length, ia, 8000);

DatagramSocket socket= new DatagramSocket();

socket.send(packet);
byte[] byte1=new byte[1024];

DatagramPacket packet1=new DatagramPacket(byte1, 0, byte1.length);
socket.receive(packet1);

String str=new String(packet1.getData(), 0, packet1.getData().length);

System.out.println("服务器的响应:"+str);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}

public static void main(String[] args) {

try {
byte[] bytes=new byte[1024];

DatagramPacket packet=new DatagramPacket(bytes, 0, bytes.length);

DatagramSocket socket =new DatagramSocket(8000);

socket.receive(packet);

String info=new String(packet.getData(), 0, packet.getData().length);

System.out.println("客户端说:"+info);

String str="我也不知道";

DatagramPacket packet1=new DatagramPacket(str.getBytes(), 0,str.getBytes().length, packet.getSocketAddress());

socket.send(packet1);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


阅读更多
想对作者说点什么?
相关热词

博主推荐

换一批

没有更多推荐了,返回首页