YMP 온라인 매뉴얼
/ 客户端(Client)示例
客户端(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); } }