1服务器pom.xml引入

     <!-- 服务端 -->
        <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.7</version>
        </dependency>
        <!-- 客户端 -->
        <dependency>
            <groupId>io.socket</groupId>
            <artifactId>socket.io-client</artifactId>
            <version>1.0.0</version>
        </dependency>

 

2:编写服务端程序 ServerDemo.java

package com.gwzx.gwzxyw.socket.test;

import org.apache.log4j.Logger;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.gwzx.gwzxyw.socket.SocketManager;

public class ServerDemo {
    private static Logger logger = Logger.getLogger(ServerDemo.class);

    public static void main(String[] args) {
        try {
            Configuration config = new Configuration();
            config.setHostname("localhost");
            config.setPort(9093);

            //此处做token认证
            config.setAuthorizationListener(new AuthorizationListener() {
                @Override
                public boolean isAuthorized(HandshakeData data) {
                    System.out.println(data);
                    return true;
                }
            });
            
            SocketIOServer server = new SocketIOServer(config);
            
            CharteventListener listner = new CharteventListener();
            listner.setServer(server);
            // chatevent为事件名称
            server.addEventListener("chatevent", ChatObject.class, listner);
            
            // 连接监听器
            server.addConnectListener(new ConnectListener() {
                @Override
                public void onConnect(SocketIOClient client) {
                    SocketManager.clietMap.put(client.getSessionId(), client);
                    logger.info("连接:SessionId=" + client.getSessionId() + ", 总数con:" + SocketManager.clietMap.size());
                }
            });

            // 断开监听器
            server.addDisconnectListener(new DisconnectListener() {
                @Override
                public void onDisconnect(SocketIOClient client) {
                    // TODO Auto-generated method stub
                    SocketManager.clietMap.remove(client.getSessionId());
                    logger.info("断开:SessionId=" + client.getSessionId() + ", 总数dis:" + SocketManager.clietMap.size());
                }
            });

            // 启动服务
            server.start();
            Thread.sleep(Integer.MAX_VALUE);
            server.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



消息实体类 ChatObject.java
package com.gwzx.gwzxyw.socket.test;

import java.io.Serializable;

public class ChatObject implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 8027556976083577023L;

    private String userName;

    private String message;

    public ChatObject() {
    }

    public ChatObject(String userName, String message) {
        this.userName = userName;
        this.message = message;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}
View Code

 

  事件处理类CharteventListener.java

package com.gwzx.gwzxyw.socket.test;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.DataListener;

public class CharteventListener implements DataListener<ChatObject> {

    SocketIOServer server;

    public void setServer(SocketIOServer server) {
        this.server = server;
    }

    @Override
    public void onData(SocketIOClient client, ChatObject data,
            AckRequest ackSender) throws Exception {
        // TODO Auto-generated method stub
        // chatevent为 事件的名称,data为发送的内容
        System.out.println("服务器收到 "+ data.getUserName() +" 消息:"+data.getMessage());
        System.out.println("服务器广播消息给borad事件");
        data.setMessage("server");
        this.server.getBroadcastOperations().sendEvent("broad", data);
    }

}
View Code

 

3:编写 JAVA 客户端

package com.gwzx.gwzxyw.socket.test;

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

import org.json.JSONException;
import org.json.JSONObject;

public class ClientDemo {
    private static Socket socket = null;
    
    public static void main(String[] args) {
        try {
            IO.Options opts = new IO.Options();  
            opts.query = "token=123456";    //传参数  
            
            socket = IO.socket("http://localhost:9093", opts);
            socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    System.out.println("客户端连接成功");
                    JSONObject json = new  JSONObject();
                    try {
                        json.put("userName", "gmh");
                        json.put("message", "gmh");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    System.out.println("客户端发送测试数据:" + json.toString());
                    socket.emit("chatevent", json);
                }
            }).on("broad", new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                     JSONObject obj = (JSONObject)args[0]; 
                     System.out.println("客户端 收到 服务器broad事件数据:" + obj);
                }
            }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
                @Override
                public void call(Object... args) {
                    System.out.println("disconnect");
                }
            });
            socket.connect();
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}
View Code

 

4:编写 JS 客户端, 当然需要下载socket.io.js 连接http://www.bootcdn.cn/socket.io/

var socket = io.connect('locahost:9093',{query: 'token=123456'});
                socket.on('connect', () => {
                    console.log("Client connect=====>socket id:" + socket.id);
                    socket.emit('chatevent', {
                        userName : "123",
                        message : "测试"
                    });
                });
                socket.on('broad', function (data) {
                    console.log(data);
                });
                socket.on('disconnect', function () {
                    console.log("Client disconnected!");
                });
                socket.on('reconnect', function () {
                    console.log("Client reconnected!");
                });
                socket.on('reconnecting', function () {
                    console.log("Client reconnecting'!");
                });
View Code

 

个人温馨提示:

  java中socket.emit(事件, 此处为org.json.JSONObject对象 )

       JSONObject 的put数据后, json.toString() 顺序是乱的

  

 

posted on 2017-09-26 18:30  1161588342  阅读(2393)  评论(0编辑  收藏  举报