java编程实现基于UDP协议传输数据的方法
本文实例讲述了java编程实现基于UDP协议传输数据的方法。分享给大家供大家参考,具体如下:
UDP协议(User Datagram Protocol,用户数据报协议)不同于TCP协议,它是不可能靠的,但是它比TCP协议具有更快的传输速度,UDP发送的数据单元称为数据报,当网络传输UDP传输UDP数据报是无法保证数据能够到达目的地,也无法保证按发送的顺序到达目的地,也就是说先发送了“hello”,再发送了“world”,但接收方可能会先收到“world”,再收到“hello”,也有可能收不到数据,为什么呢?因为它是不可能靠的,在传输途中可能丢失了。但UDP比TCP跟适合与传输实时音频。下面是一个简单的UPD传输数据报的例子
服务器端:
import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class EchoServer { private DatagramSocket datagramSocket; private final int port = 8088; public static void main(String[] args) throws SocketException { new EchoServer().service(); } public EchoServer() throws SocketException{ datagramSocket = new DatagramSocket(port); System.out.println("服务器启动"); } public String echo(String msg){ return "echo:"+msg; } public void service(){ while (true) { try { DatagramPacket packet = new DatagramPacket(new byte[512], 512); datagramSocket.receive(packet); String msg = new String(packet.getData(), 0, packet.getLength()); System.out.println(packet.getAddress()+"/"+packet.getPort()+" msg:"+msg); packet.setData(echo(msg).getBytes()); datagramSocket.send(packet); } catch (IOException e) { e.printStackTrace(); } } } }
客户端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; public class EchoClient { private String remoteHost="localhost"; private int remotePort=8088; private DatagramSocket datagramSocket; public EchoClient() throws SocketException{ datagramSocket = new DatagramSocket(); } public static void main(String[] args) throws SocketException { new EchoClient().talk(); } public void talk(){ try { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; InetAddress address = InetAddress.getByName(remoteHost); while ((msg=reader.readLine())!=null) { //发送数据报 byte [] buffer = msg.getBytes(); DatagramPacket packet = new DatagramPacket(buffer,buffer.length, address, remotePort); datagramSocket.send(packet); //接收数据报 DatagramPacket inputPacket = new DatagramPacket(new byte[512], 512); datagramSocket.receive(inputPacket); System.out.println(new String(inputPacket.getData(), 0 , inputPacket.getLength())); if("bye".equals(msg)){ break; } } } catch (IOException e) { e.printStackTrace(); }finally{ datagramSocket.close(); } }
希望本文所述对大家Java程序设计有所帮助。
赞 (0)