此源码分析基于 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 &#