vertx写udp server

1,最新版本vertx有udp支持,试着写一个UDP Server接收客户端发过来到心跳

import org.vertx.java.core.AsyncResult;
import org.vertx.java.core.AsyncResultHandler;
import org.vertx.java.core.Handler;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.datagram.DatagramPacket;
import org.vertx.java.core.datagram.DatagramSocket;
import org.vertx.java.core.datagram.InternetProtocolFamily;
import org.vertx.java.core.logging.Logger;
import org.vertx.java.platform.Verticle;
public class HeartBeatServer extends Verticle {
    Logger logger;
    private static final int TS_SIZE = 8;
    private static final int CMD_SIZE = 1;
    private static final int UID_SIZE = 4;
    private static final int TS_IDX = 0;
    private static final int CMD_IDX = TS_SIZE;
    private static final int UID_IDX = TS_SIZE + CMD_SIZE;
    private static final int CID_IDX = TS_SIZE + CMD_SIZE + UID_SIZE;
    public void start() {
        logger = container.logger();
        final DatagramSocket socket = vertx
                .createDatagramSocket(InternetProtocolFamily.IPv4);
        socket.listen("0.0.0.0", 8888,
                new AsyncResultHandler<DatagramSocket>() {
                    public void handle(AsyncResult<DatagramSocket> asyncResult) {
                        if (asyncResult.succeeded()) {
                            socket.dataHandler(new Handler<DatagramPacket>() {
                                public void handle(DatagramPacket packet) {
                                    Buffer buf = packet.data();//bu
                                    logger.info(buf.length());
                                    int ts = buf.getInt(TS_IDX);
                                    byte cmd = buf.getByte(CMD_IDX);
                                    int uid = buf.getInt(UID_IDX); // 客服端已经替换为网络字节序
                                    int cid = buf.getInt(CID_IDX);
                                    logger.info("ts:" + ts + ",cmd:" + cmd
                                            + ",uid:" + uid + ",cid:" + cid);
                                }
                            });
                        } else {
                            logger.warn("Listen failed", asyncResult.cause());
                        }
                    }
                });
    }
}

说明:Buffer是对netty的ByteBuf封装,就可以当作byte array来用


2,用python写个客户端

import socket,time
from struct import *
SERVER_IP = '192.168.1.162'; SERVER_PORT = 8888; BEAT_PERIOD = 0.1
print ('Sending heartbeat to IP %s , port %d' % (SERVER_IP, SERVER_PORT))
print ('press Ctrl-C to stop')
tick = 1
while True:
    ts = int(time.time())
    data = pack('>ibii',ts,1,tick,3)
    hbSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    hbSocket.sendto(data, (SERVER_IP, SERVER_PORT))
    tick += 1
    print tick
    if __debug__:
        print'Time: %s' % time.ctime( )
        time.sleep(BEAT_PERIOD)

用pack命令把数据pack为网络字节序

你可能感兴趣的:(java,server,UDP,Vertx)