android UDP

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

2.jpg

1.jpg

示例代码:
服务器端:
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值