线上聊天 整理了下netty socket.io

来源:互联网 发布:mac怎么编辑pdf文件 编辑:程序博客网 时间:2024/05/29 14:20
主要是参考:http://blog.csdn.net/sun_t89/article/details/52060946


首先在pom.xml中加入:
 <dependency>
            <groupId>com.corundumstudio.socketio</groupId>
            <artifactId>netty-socketio</artifactId>
            <version>1.7.11</version>
        </dependency>






import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;




import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
//http://start.spring.io/
@Configuration
@ComponentScan("com.gy")
@EnableAutoConfiguration
@EnableFeignClients("com.gy.api")
/*@EnableScheduling*/
public class Application extends SpringBootServletInitializer {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }


    //如果以下这个去掉,WebMvcBoot方可生效!
 /*  @Bean(name = "exceptionFilter")
    public ExceptionFilter exceptionFilter() {
        return new ExceptionFilter();
    }*/




    @Bean
    public SocketIOServer socketIOServer()
    {
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setHostname("localhost");
        config.setPort(8081);


        config.setAuthorizationListener(new AuthorizationListener() {//类似过滤器
            @Override
            public boolean isAuthorized(HandshakeData data) {
                //http://localhost:8081?username=test&password=test
                //例如果使用上面的链接进行connect,可以使用如下代码获取用户密码信息,本文不做身份验证
// String username = data.getSingleUrlParam("username");
// String password = data.getSingleUrlParam("password");
                return true;
            }
        });


        final SocketIOServer server = new SocketIOServer(config);
        return server;
    }


    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }
}








监听程序:
package com.gy.config.ntt;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;


@Component
public class MessageEventHandler
{
    private final SocketIOServer server;
    @Autowired
    public MessageEventHandler(SocketIOServer server)
    {
        this.server = server;
    }
    @OnConnect
    public void onConnect(SocketIOClient client)
    {
        String clientId = client.getHandshakeData().getSingleUrlParam("clientid");
        System.out.println("断开连接:"+clientId);
    }
    @OnDisconnect
    public void onDisconnect(SocketIOClient client)
    {
        String clientId = client.getHandshakeData().getSingleUrlParam("clientid");
        System.out.println("已连接:"+clientId);
    }


    @OnEvent(value = "messageevent")
    public void onEvent(SocketIOClient client, AckRequest request, MessageInfo data)
    {
        System.out.println("发来消息:"+data.getMsgContent());
        server.getClient(client.getSessionId()).sendEvent("messageevent", "back data");
    }
}


启动:


import com.corundumstudio.socketio.SocketIOServer;
import com.gy.constants.InitProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=1)
public class MyCommandLineRunner implements CommandLineRunner {
    private final SocketIOServer server;


    @Autowired
    public MyCommandLineRunner(SocketIOServer server) {
        this.server = server;
    }


    @Override
    public void run(String... args) throws Exception {
        server.start();
        System.out.println("....启动成功!");
    }
}


服务端已完成 了,如果启动没有异常就成功了。




//客户端配置见:http://www.jianshu.com/p/d9b1273a93fd


这里说下要点:

Node.js官网下载安装

https://nodejs.org/download/

环境变量中path中加下:C:\Program Files\nodejs\

查看安装成功:
node -v  
npm -v  


package.json
{
  "name": "realtime-server",
  "version": "0.0.1",
  "description": "my first realtime server",
  "dependencies": {}
}


我这里的package.json目录在:C:\Users\Administrator
运行以下:
npm install --save express
npm install --save socket.io


在同一目录下新建:`index.js`
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);


app.get('/', function(req, res){
    res.send('<h1>Welcome Realtime Server</h1>');
});


http.listen(3000, function(){
    console.log('listening on *:3000');
});
命令行运行node index.js
如果没有问题运行一下:
http://localhost:3000


出现:
Welcome Realtime Server


在客户端的html中可以引用:
   <script src="http://localhost:3000/socket.io/socket.io.js"></script>


这是以下页面的内容:


<!DOCTYPE html>  
<html>  
<head>  
  
        <meta charset="utf-8" />  
  
        <title>Demo Chat</title>  
  
        <link href="bootstrap.css" rel="stylesheet">  
  
    <style>  
        body {  
            padding:20px;  
        }  
        #console {  
            height: 400px;  
            overflow: auto;  
        }  
        .username-msg {color:orange;}  
        .connect-msg {color:green;}  
        .disconnect-msg {color:red;}  
        .send-msg {color:#888}  
    </style>  
  
  
   <script src="http://localhost:3000/socket.io/socket.io.js"></script>
        <script src="moment.min.js"></script>  
        <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>  
  
    <script>  
  
        var clientid = 'testclient1';  
        var targetClientId= 'testclient2';  
          
        var socket =  io.connect('http://localhost:8081?clientid='+clientid);  
  
        socket.on('connect', function() {  
            output('<span class="connect-msg">Client has connected to the server!</span>');  
        });  
  
        socket.on('messageevent', function(data) {  
alert('back......');
            alert('<span class="username-msg">' + data.sourceClientId + ':</span> ' + data.msgContent);  
        });  
  
        socket.on('disconnect', function() {  
            output('<span class="disconnect-msg">The client has disconnected!</span>');  
        });  
  
                function sendDisconnect() {  
                        socket.disconnect();  
                }  
  
        function sendMessage() {  
                        var message = $('#msg').val();  
                        $('#msg').val('');  
  
                        var jsonObject = {sourceClientId: clientid,  
                                          targetClientId: targetClientId,  
                                          msgType: 'chat',  
                                          msgContent: message};  
                        socket.emit('messageevent', jsonObject);  
        }  
  
        function output(message) {  
                        var currentTime = "<span class='time'>" +  moment().format('HH:mm:ss.SSS') + "</span>";  
                        var element = $("<div>" + currentTime + " " + message + "</div>");  
            $('#console').prepend(element);  
        }  
  
        $(document).keydown(function(e){  
            if(e.keyCode == 13) {  
                $('#send').click();  
            }  
        });  
    </script>  
</head>  
  
<body>  
  
    <h1>Netty-socketio Demo Chat</h1>  
  
    <br/>  
  
    <div id="console" class="well">  
    </div>  
  
        <form class="well form-inline" onsubmit="return false;">  
           <input id="msg" class="input-xlarge" type="text" placeholder="Type something..."/>  
           <button type="button" onClick="sendMessage()" class="btn" id="send">Send</button>  
           <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>  
        </form>  
  
  
  
</body>  
  

</html>  


注意:

1、客户端出现以下报错

GET http://192.168.1.104:8081/socket.io/?clientid=testclient1&EIO=3&transport=polling&t=L_CkXSC net::ERR_CONNECTION_REFUSED

那是由于你所访问的服务端设置的IP与你的IP不对应,如我以上设置为localhost,只能本地测试,如果要其他人也能调用,请改成IP地址 调用。

服务端和客户端都要改。

2、测试时,如果关闭了node index.js的监听窗口,则http:localhost:3000也会失效的,那socket.io.js也就访问不到了,所以要一直开着的。

3、双方要通信,client.getSessionId()要保存下来才能进行通信。



原创粉丝点击