简体   繁体   English

在Websocket中添加自定义数据

[英]Adding custom data in Websocket

I would like to send the logged in client side username to a websocket script along with the message the client has entered. 我想将登录的客户端用户名与客户端输入的消息一起发送到websocket脚本。 I need support on implementing another variable- rge username, to be sent with the message. 我需要支持实现另一个可变的用户名,并与消息一起发送。 Right now I'm using: https://github.com/Flynsarmy/PHPWebSocket-Chat and the js is 现在我正在使用: https : //github.com/Flynsarmy/PHPWebSocket-Chat和js是

Server.send( 'message', text );

with Server being the FancyWebSocket.This is sent to: 服务器为FancyWebSocket,发送到:

var FancyWebSocket = function(url)
{
    var callbacks = {};
    var ws_url = url;
    var conn;

    this.bind = function(event_name, callback){
        callbacks[event_name] = callbacks[event_name] || [];
        callbacks[event_name].push(callback);
        return this;// chainable
    };

    this.send = function(event_name, event_data){
        this.conn.send( event_data );
        return this;
    };

    this.connect = function() {
        if ( typeof(MozWebSocket) == 'function' )
            this.conn = new MozWebSocket(url);
        else
            this.conn = new WebSocket(url);

        // dispatch to the right handlers
        this.conn.onmessage = function(evt){
            dispatch('message', evt.data);
        };

        this.conn.onclose = function(){dispatch('close',null)}
        this.conn.onopen = function(){dispatch('open',null)}
    };

    this.disconnect = function() {
        this.conn.close();
    };

    var dispatch = function(event_name, message){
        var chain = callbacks[event_name];
        if(typeof chain == 'undefined') return; // no callbacks for this event
        for(var i = 0; i < chain.length; i++){
            chain[i]( message )
        }
    }
};

Which is binded to my server.php as: 绑定到我的server.php为:

$Server->bind('message', 'wsOnMessage');    
function wsOnMessage($clientID, $message, $messageLength, $binary)

It is up to you which content you send. 由您决定要发送的内容。 You could for example send it like 例如,您可以像这样发送

Server.send("USERNAME|message", text);

Then you can extract the USERNAME on the server by splitting the received string at the pipe | 然后你就可以在管道拆分接收到的字符串中提取的服务器上的用户名| symbol. 符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM