Contoh pelanggan
Parameter pemulaan pelanggan:
#------------------------------------- # 服务模块--客户端初始化参数 #------------------------------------- # 客户端配置列表,多个客户端名称间用'|'分隔,默认为default ymp.configs.serv.client.name_list=default # 服务名称, 默认为default ymp.configs.serv.client.default.name=default # 远程主机IP地址, 默认为0.0.0.0 ymp.configs.serv.client.default.host=0.0.0.0 # 远程主机端口号, 默认为8281 ymp.configs.serv.client.default.port=8281 # 编解码字符集, 默认为UTF-8 ymp.configs.serv.client.default.charset=UTF-8 # 缓冲区大小, 默认为4096 ymp.configs.serv.client.default.buffer_size=4096 # 执行线程池大小, 默认为10 ymp.configs.serv.client.default.executor_count=10 # 连接超时时间(秒), 默认为30 ymp.configs.serv.client.default.connection_timeout=30 # 心跳发送时间间隔(秒), 默认为60 ymp.configs.serv.client.default.heartbeat_interval=60 # 自定义参数, 可选 ymp.configs.serv.client.default.params.xxx=xxx
Mewakili pelanggan dengan mengisytiharkan anotasi @Client dalam kelas pelaksanaan pendengar Anotasi mempunyai parameter berikut:
berdasarkan protokol TCPheri, Pelanggan kepada keperluan
. Kelas pendengar NioClientListener menyokong mendengar acara berikut:
Pelanggan berdasarkan protokol UDP perlu mewarisi kelas pendengar NioUdpListener dan menyokong mendengar acara berikut:
Kod klien TC
@Client(reconnectClass = DefaultReconnectService.class, hearbeatClass = DefaultHeartbeatService.class, codec = TextLineCodec.class) public class TcpClient extends NioClientListener { @Override public void onSessionConnected(INioSession session) throws IOException { super.onSessionConnected(session); // session.send("Hello from client."); } @Override public void onMessageReceived(Object message, INioSession session) throws IOException { super.onMessageReceived(message, session); // System.out.println(session + "--->" + message); } @Override public void onExceptionCaught(Throwable e, INioSession session) throws IOException { System.out.println(session + "--->" + e.getMessage(), e); } }
Pelanggan UDP
@Client(implClass = NioUdpClient.class, codec = TextLineCodec.class) public class UdpClient extends NioUdpListener { public Object onSessionReady() throws IOException { return "Hello from client."; } public Object onMessageReceived(InetSocketAddress sourceAddr, Object message) throws IOException { System.out.println(sourceAddr + "--->" + message); return null; } public void onExceptionCaught(InetSocketAddress sourceAddr, Throwable e) throws IOException { System.out.println(sourceAddr + "--->" + e); } }