android UDP

针对UDP的DatagramSocket、DatagramPackage
1.对于UDP服务端,首先启动侦听服务,然后得到数据包进行处理,组后根据获得数据包进行反馈。
2.UDP socket没有连接的概念,因此构造完成的DatagramSocket不会发出向对端的网络连接请求,在每一个发送的UDP数据包中包含目的地址和端口。因为UDP数据不会在对端进行重新组包,因此一次发送的数据长度必须加以限制。Socket.send(outputPacket);用于发送一个数据包;socket.receive(inputPacket);用于接收一个数据包。

android UDP

android UDP

示例代码:
服务器端:
public class UDPServer{
public static void main(String[] args) throws Exception{
DatagramSocket udpSocket = new DatagramSocket(8000);
while(true){
try{
// UDP数据读取
DatagramPacket packet = new DatagramPacket(new byte[512],512);
udpSocket.receive(packet);
String msg = new String(packet.getData()), 0,packet.getLength());
System.out.println(msg);
if(msg.equals("exit")){
break;
}

// UDP数据发送
SimpleDateFormat f = new SimpleDateFormat("MMM dd,yyyy kk:mm:ss");
String time = "现在的时间是:" + f.format(new Date());
packet.setData(time.getBytes());
udpSocket.send(packet);

}catch(Exception e){
e.printStackTrace();
}
}
udpSocket.close();
}
}


客户端:
public void client(){
InetAddress remoteIP;
try {
remoteIP = InetAddress.getByName("localhost");
DatagramSocket socket = new DatagramSocket();
} catch (UnknownHostException e1) {
e1.printStackTrace();
}

BufferedReader wt = new BufferedReader (new InputStreamReader(System.in));
System.out.println("input one line ,user \"exit\" to quit the server ");
while(true){
try{
// 读取输入
String str = wt.readLine();
byte[] outputData = str.getBytes();
// UDP socket 数据发送
DatagramPacket outputPacket = new DatagramPacket(outputData,outputData.length,remoteIP,8000);
socket.send(outputPacket);
if(str.equals("exit")){
//udp 数据读取
DatagramPacket inputPacket = new DatagramPacket(new byte[512],512);
socket.receive(inputPacket);
System.out.println(new String(inputPacket.getData(),0,inputPacket.getLength()));

}
}catch(Exception e){
e.printStackTrace();
}
}
socket.close();

}

转载http://www.apkbus.com/forum.php?mod=viewthread&tid=13316&fromuid=3402