socket IO java的使用

             因为项目中有用到socket io 然后呢,老大只给了js版本的,但是需要在服务端也要用到,所以,就写了以下的测试代码.

maven需要导入的


  
    io.socket
    socket.io-client
    0.8.3
  

测试的Demo代码:


package io.mycat.bigmem.buffer;

import org.json.JSONObject;

import io.socket.emitter.Emitter;
import io.socket.engineio.client.Socket;

public class testSocket {
	public static void main(String[] args)  {
		System.out.println(111);
		Socket socket ;
		try {
			
			socket = new Socket("ws://host/?user_id=xs01&user_name=xs01");
			//socket = new Socket("ws://localhost");
//			socket.on(Socket.EVENT_OPEN, new Emitter.Listener() {
//			  @Override
//			  public void call(Object... args) {
//			    //socket.send("hi");
//			    socket.close();
//			  }
//			});
			socket.open();
			
			//socket.connect();
			
			// Receiving an object
			socket.on("broadcast event", new Emitter.Listener() {
			  @Override
			  public void call(Object... args) {
			    JSONObject obj = (JSONObject)args[0];
			    System.out.println(obj.toString());
			  }
			});
			
			JSONObject obj = new JSONObject();
			obj.put("uuid", "123");
			socket.emit("join info", obj);
			
			
			// Sending an object
			
			
			while(true) {
				System.out.println("===");
				obj = new JSONObject();
				obj.put("user_id", "xs01");
				obj.put("user_name", "xs01");
				obj.put("score", "100");

				socket.emit("broadcast event", obj);
				Thread.currentThread().sleep(1000);
				socket.close();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

参考的网站:

https://github.com/socketio/socket.io-client-java


你可能感兴趣的:(socket IO java的使用)