`
lzj0470
  • 浏览: 1247164 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

UDP协议下发送

    博客分类:
  • java
阅读更多

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;

public class TestIPMSG {

   public static void main(String[] args) {
         DatagramSocket socket;
         InetAddress address;

         long IPMSG_SENDMSG = 0x00000020;

         String SENDER = "张恩明";
         String HOST = "localhost";
         String MSG_CONTENT = "我要死了";

         try {
             socket = new DatagramSocket();
             address = InetAddress.getByName("192.168.1.18");// 发送给消息的地址

             /**
              * IPMSG收发数据包的格式(一行):
              *
              * version(IPMSG版本):no(消息编号,可以用系统时间):user(发送消息的用户名):
              * host(发送消息的主机名):command(上述 Command 常量,可以用 | 组合多个值):
              * msg(消息内容)
              */
             byte[] buffer = ("1:" + new Date().getTime() + ":" + SENDER + ":"
                     + HOST + ":" + IPMSG_SENDMSG + ":" + MSG_CONTENT)
                     .getBytes();

             DatagramPacket packet = new DatagramPacket(buffer, buffer.length,
                     address, 2425);
             socket.send(packet); // 发送报文
    
             packet = new DatagramPacket(buffer, buffer.length);
             socket.receive(packet);// 接收回应

             String message = new String(packet.getData()); // 得到报文信息

             System.out.println(message); // 显示对方返回的信息
            
         } catch (UnknownHostException e) {
             e.printStackTrace();
         } catch (SocketException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }

     }

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics