客戶端(Client)範例
客戶端初始化參數:
#------------------------------------- # 服务模块--客户端初始化参数 #------------------------------------- # 客户端配置列表,多个客户端名称间用'|'分隔,默认为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
#透過在監聽器實作類別宣告@Client註解來表示一個客戶端,該註解有如下參數:
基於TCP協定的客戶端,需要繼承NioClientListener監聽器類,支援監聽如下事件:
基於UDP協定的客戶端,需要繼承NioUdpListener監聽器類,支援監聽如下事件:
範例程式碼
TCP客戶端
@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); } }
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); } }