分析JAVA源码socket_websocket的那些事 - socket.io-client-java源码浅析

此源码分析基于 socket.io-client-java  0.9.0

先来个 socket.io-client-java 客户端实例:

import java.net.URISyntaxException;

import java.util.Scanner;

import com.itdreamer.util.DataUtil;

import io.socket.client.IO;

import io.socket.client.Socket;

import io.socket.emitter.Emitter;

public class Client {

public static void main(String[] args) throws URISyntaxException, InterruptedException {

IO.Options options = new IO.Options();

options.transports = new String[]{"websocket"};

options.reconnectionAttempts = 2;

//失败重连的时间间隔

options.reconnectionDelay = 1000;

//连接超时时间(ms)

options.timeout = 500;

final Socket socket = IO.socket("http://localhost:8090", options);

socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

@Override

public void call(Object... args) {

System.out.println(DataUtil.getCurrentDataTime() + ":client connect! ");

socket.send("hello server, my name is client");

}

});

socket.on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {

@Override

public void call(Object... args) {

System.out.println(DataUtil.getCurrentDataTime() + ":client disconnect!");

}

});

socket.on(Socket.EVENT_MESSAGE, new Emitter.Listener() {

@Override

public void call(Object... args) {

for (Object obj : args) {

System.out.println(DataUtil.getCurrentDataTime() + ":receive server message="+obj);

}

}

});

socket.connect();

System.out.println(DataUtil.getCurrentDataTime() + ":client console input......");

Scanner sc = new Scanner(System.in);

while (sc.hasNext()) {

String message = sc.next();

System.out.println(DataUtil.getCurrentDataTime() + ":client console send data="+message);

socket.send(message);

}

}

}

socket.io-client-java 封装得很不错,只要简单几个方法,把自己的业务逻辑实现就搞定了。

本方从以下两个方面进行分析:

1、socket 连接是如何创建的

2、服务端响应的信息是如何接收并调用定义事件对应Listener的

socket 连接是如何创建的

连接门面对象

io.socket.client.Socket

入口方法

socket.connect();

/**

* Connects the socket.

*/

public Socket connect() {

return this.open();

}

/**

* Connects the socket.

*/

public Socket open() {

EventThread.exec(new Runnable() {

@Override

public void run() {

if (Socket.this.connected) return;

Socket.this.subEvents();

Socket.this.io.open(); // ensure open

if (Manager.ReadyState.OPEN &#

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值