sta / websocket-sharp

A C# implementation of the WebSocket protocol client and server
http://sta.github.io/websocket-sharp
MIT License
5.71k stars 1.66k forks source link

How to distinguish each connection #348

Open daodol opened 7 years ago

daodol commented 7 years ago

I would like to achieve one to one to send information, but I can not distinguish between each user's connection,Have Session or Uid?Can you write an example? THANK YOU!

systemidx commented 7 years ago

WebSocketSharp.Server.WebSocketBehavior has a property called ID which is unique to each session.

systemidx commented 7 years ago

Here's a snippet of how I handle authentication and utilize the unique ID (in addition to the passed-in ID, which may not be unique if the client is logging in from two devices)

protected override async void OnOpen()
        {
            //Build authentication request
            IAuthenticationRequest request = new AuthenticationRequest {Parameters = this.Context.QueryString.ToDictionary()};
            IAuthenticationResponse response = await _authenticationHandler.Authenticate(request);

            if (response == null || !response.IsAuthenticated)
            {
                this.Context.WebSocket.Close(CloseStatusCode.PolicyViolation);

                await _logger.Warn($"User attempted connection with invalid UID or token.\tUID: {this.Context.GetUsername()}");
                return;
            }

            //Get the data elements
            string uid = this.Context.GetUsername();
            string uniqueId = this.ID;

            //Set the metadata in this object (necessary anymore?)
            this.Metadata["uid"] = uid;

            //Push the data to the logon queue for processing by a subsequent process
            _queueLogOn.PushMessage(new ClientIdentifier { Uid = uid, UniqueId = uniqueId });

            //Send the data to the client
            IPacket packet = await Packet.EncodePacket(response, "Authentication", "Authenticate", null, uid);
            this.Context.Send(packet);

            base.OnOpen();
        }