Socket编程---使用无连接的数据报(UDP) 进行通信(转)
使用无连接的数据报(UDP) 进行通信
什么是Datagram?
数据报是网上传输的独立数据包 ,数据报是否能正确地到达目的地,到达的时间,顺序,内容的正确性均没有保障。
java中使用Datagram与DatagramPacket类
DatagramSocket类利用UDP协议来实现客户与服务器的Socket.
send():发送数据报
receive(): 接收数据报
以下为流程
以下为简单示例,不含一些异常处理、判空处理。
一、服务器端
- package com.network;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class UDPServer
- {
- public static void main(String[] args)throws Exception
- {
- DatagramSocket datagramSocket = new DatagramSocket(5678);
- byte[] buffer = new byte[100];
- DatagramPacket packet = new DatagramPacket(buffer,100);
- datagramSocket.receive(packet);
- byte[] data = packet.getData();
- int i = packet.getLength();
- String content = new String(data,0,i);
- System.out.println("content from client : " + content);
- int length = content.length();
- String strLength = String.valueOf(length);
- byte[] b = strLength.getBytes();
- InetAddress address = packet.getAddress();
- int port = packet.getPort();
- DatagramPacket packet2 = new DatagramPacket(b,b.length,address,port);
- System.out.println("length: " + new String(b,0,b.length));
- datagramSocket.send(packet2);
- datagramSocket.close();
- }
- }
二、客户端
- package com.network;
- import java.net.DatagramPacket;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- public class UDPClient
- {
- public static void main(String[] args) throws Exception
- {
- DatagramSocket datagramSocket = new DatagramSocket();
- String content = "hello world!";
- byte[] buffer = content.getBytes();
- InetAddress address = InetAddress.getByName("localhost");
- DatagramPacket packet = new DatagramPacket(buffer,buffer.length,address,5678);
- datagramSocket.send(packet);
- byte[] b = new byte[100];
- DatagramPacket packet2 = new DatagramPacket(b,100);
- datagramSocket.receive(packet2);
- byte[] b2 = packet2.getData();
- int l = packet2.getLength();
- String str = new String(b2,0,l);
- System.out.println("length of string : " + str);
- datagramSocket.close();
- }
- }