See section 6.2 of the WebSocket spec for how this algorithm is suppose to work
175391
public Set<EndpointHelper> determineEndpoints(Set<EndpointHelper> annotatedEndpointHelpers,
                                                  Set<EndpointHelper> programmaticEndpointHelpers,
                                                  Set<Class<? extends ServerApplicationConfig>> serverAppConfigs) {

        Set<Class<?>> annotatedEndpointClasses = new HashSet<Class<?>>();
        HashMap<Class<?>, EndpointHelper> endpointMap = new HashMap<Class<?>, EndpointHelper>();
        Set<EndpointHelper> returnHelpers = new HashSet<EndpointHelper>();

        Set<Class<? extends Endpoint>> programmaticEndpointClasses = new HashSet<Class<? extends Endpoint>>();
        Set<Class<? extends ServerEndpointConfig>> endpointConfigs = new HashSet<Class<? extends ServerEndpointConfig>>();

        // no ServerApplicationConfig objects, allow all the annotated endpoints through, but no programmatic endpoints
        if (serverAppConfigs.size() == 0) {
            return annotatedEndpointHelpers;
        }

        // first look at annotated Endpoints
        // build the set of annotated Endpoints to look through, also need a map of endpoints to helpers for later indexing
        for (EndpointHelper helper : annotatedEndpointHelpers) {
            Class<?> c = helper.getEndpointClass();
            annotatedEndpointClasses.add(c);
            // need a map of EndpointClass to EndpointHelper to index into later
            endpointMap.put(c, helper);
        }

        // if we have annotated endpoints, then pass the set of them to each user config object
        if (annotatedEndpointClasses.size() > 0) {
            for (Class<? extends ServerApplicationConfig> configClass : serverAppConfigs) {
                ServerApplicationConfig config = null;
                try {
                    config = configClass.newInstance();
                } catch (IllegalAccessException e) {
                    // allow instrumented FFDC to be used here
                } catch (InstantiationException e) {
                    // allow instrumented FFDC to be used here
                }

                if (config != null) {
                    // get from the user config object the configs for which endpoints to use
                    Set<Class<?>> annotatedEnpointsToUse = config.getAnnotatedEndpointClasses(annotatedEndpointClasses);

                    // for each returned endpoint class, find the endpoint helper and put it into the return set
                    for (Class<?> c : annotatedEnpointsToUse) {
                        EndpointHelper helper = endpointMap.get(c);
                        if (tc.isDebugEnabled()) {
                            Tr.debug(tc, "will use annoated endpoint of: " + c);
                        }
                        returnHelpers.add(helper);
                    }
                }
            }
        }

        // now do the same with programmatic configs.
        // first look at programmatic Endpoints
        // build the set of programmatic Endpoints to look through, also need a map of endpoints to helpers for later indexing
        endpointMap.clear();
        for (EndpointHelper helper : programmaticEndpointHelpers) {
            Class<?> c = helper.getEndpointClass();
            programmaticEndpointClasses.add((Class<? extends Endpoint>) c);
            // need a map of EndpointClass to EndpointHelper to index into later
            endpointMap.put(c, helper);
        }

        // if we have programmatic endpoints, then pass the set of them to each user config object
        if (programmaticEndpointClasses.size() > 0) {
            for (Class<? extends ServerApplicationConfig> configClass : serverAppConfigs) {
                ServerApplicationConfig config = null;
                try {
                    config = configClass.newInstance();
                } catch (IllegalAccessException e) {
                    // allow instrumented FFDC to be used here
                } catch (InstantiationException e) {
                    // allow instrumented FFDC to be used here
                }

                if (config != null) {
                    // get from the user config object which of the programmatic endpoints to use
                    Set<ServerEndpointConfig> programmaticEnpointConfigsToUse = config.getEndpointConfigs(programmaticEndpointClasses);
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, "programmaticEnpointConfigsToUse: " + programmaticEnpointConfigsToUse);
                    }
                    if (programmaticEnpointConfigsToUse != null) {
                        // for each returned endpoint config class, create the endpoint helper and put it into the return set
                        for (ServerEndpointConfig endpointConfig : programmaticEnpointConfigsToUse) {

                            Class<?> endpoint = endpointConfig.getEndpointClass();
                            // Question: is this really how we should map the endpoint from the user config, to the endpoint we scanned earlier?
                            // You can map a single endpoint to multiple URIs/configurators, etc, so creating new here.
                            if (tc.isDebugEnabled()) {
                                Tr.debug(tc, "endpointConfig class: " + endpoint.getName());
                            }
                            EndpointHelper scannedHelper = endpointMap.get(endpoint);
                            if (scannedHelper != null) {
                                EndpointHelper newHelper = new EndpointHelper();
                                newHelper.setEndpointClass(scannedHelper.getEndpointClass());

                                newHelper.setServerEndpointConfig(endpointConfig);
                                if (tc.isDebugEnabled()) {
                                    Tr.debug(tc, "will use programmatic endpoint of: " + endpoint);
                                }
                                returnHelpers.add(newHelper);
                            }
                        }
                    }
                }
            }
        }

        return returnHelpers;
    }
578322
function() {
        if(!this.ws || this.ws.readyState !== WebSocket.OPEN) {
            if(this.debug >= 1)
                this.log('[warning] spectate() was called when connection was not established, packet will be dropped');
            return false;
        }

        var buf = new Buffer([1]);
        this.send(buf);

        return true;
    }
458449
function (config) {

    // check parameters
    if ((typeof config.IN_PORT !== 'number' && 
        typeof config.OUT_PORT !== 'number')) {
    
        LOG.warn('config needs to define parameters: IN_PORT or OUT_PORT');
        return; 
    }
	
	var server_type = config.type || 'MPEG';

    var STREAM_SECRET = config.secret;
		IN_PORT = config.IN_PORT || 8082,
		OUT_PORT = config.OUT_PORT || 8084,
		STREAM_MAGSR_BYTES = 'jsmp'; // Must be 4 bytes
		
	// channel info
	var l_channels = {};
        
    var socketServer = undefined;
    var streamServer = undefined;

    this.start = function () {
    
        // Websocket Server
        socketServer = new (require('ws').Server)({port: OUT_PORT});
		
		// process incoming connection of subscribers
        socketServer.on('connection', function (socket) {

			// generate unique clientID
			var clientID = UTIL.createUUID();
			var clientData = socketServer.clients[socketServer.clients.length - 1];
			
			var channel = undefined;
			LOG.sys( 'New WebSocket Connection (' + socketServer.clients.length + ' total) id: ' + clientID );
					 
			// we start to handle after receiving channel name to subscribe
			// NOTE: the incoming content is not string type
			socket.on('message', function (name) {

                try {
 
                    /*
					var obj = JSON.parse(name.data);
					LOG.warn(obj);
					*/
                    
					// extract info
					if (l_channels.hasOwnProperty(name) === false) {
						var msg = 'no stream registered for channel [' + name + ']';
						LOG.warn(msg);
						socket.send(msg);
						return;
					}
					
					// record channel name
					channel = name;
					
					// get parameters
					var params = l_channels[channel].para;
		        
					// NOTE: we convert string to numbers with | 0			
					var width = (params[0] || 320) | 0;
					var height = (params[1] || 240) | 0;
					
					LOG.warn('params:');
					LOG.warn(params);
					LOG.warn('client to receive channel: ' + channel + ' w: ' + width + ' h: ' + height);
                
					// record this user's reference as part of the channel subscribers
					// NOTE: we record clientData, not socket
					l_channels[channel].users[clientID] = clientData;   
					
					LOG.warn('channel [' + channel + '] has ' + Object.keys(l_channels[channel].users).length + ' users', 'message');
					
					// Send back magic bytes and video size to the newly connected socket
					// struct { char magic[4]; unsigned short width, height;}
					var streamHeader = new Buffer(8);
					streamHeader.write(STREAM_MAGSR_BYTES);
					streamHeader.writeUInt16BE(width, 4);
					streamHeader.writeUInt16BE(height, 6);
					socket.send(streamHeader, {binary:true}); 
                
                }
                catch(e) {
                    LOG.error(e);
                }    
			});
			
			// handles closing in-coming connection
			socket.on('close', function (code, message) {
				LOG.sys( 'Disconnected WebSocket (' + socketServer.clients.length + ' total)' );
				
				// remove user record (i.e., socket) from channel
				if (l_channels.hasOwnProperty(channel)) {		
					delete l_channels[channel].users[clientID];
					LOG.warn('client [' + clientID + '] unsubscribe from channel [' + channel + ']');
				}
			});
        });
    
        socketServer.broadcast = function (channel, data, opts) {
		
			// go over all clients for a given channel
			if (l_channels.hasOwnProperty(channel) === false) {
				LOG.warn('channel [' + channel + '] not registered, cannot broadcast');
				return;
			}
			//LOG.warn('channel [' + channel + '] has ' + Object.keys(l_channels[channel].users).length + ' users', 'broadcast');
			
			var clients = l_channels[channel].users;
			
			for (var id in clients) {
				
				try {
					//this.clients[i].send(data, opts);
					clients[id].send(data, opts);
				}
				catch(e) {
					LOG.warn('client[' + id + '] fails to send to channel [' + channel + ']');
				}
			}
        };
    
        // HTTP Server to accept incoming MPEG Stream
        streamServer = require('http').createServer(function (request, response) {
			var params = request.url.substr(1).split('/');			
			var channel = params[0];
        
			if (channel) {
				LOG.sys(
					'Stream Connected: ' + request.socket.remoteAddress + 
					':' + request.socket.remotePort + ' channel: ' + channel
				);
				
				//' size: ' + width + 'x' + height
				
				
				// remove first element (channel name) and store the rest as parameters
				params.splice(0, 1);
				l_channels[channel] = {
					para: params,		// app-specific parameters in string array format
					users: {}			// user clients conneted awating message updates
				}
				
				request.on('data', function(data) {
					if (socketServer)
						socketServer.broadcast(channel, data, {binary:true});
				});
			}
			else {
				LOG.sys(
					'failed connection: '+ request.socket.remoteAddress + 
					request.socket.remotePort + ' - no channel specified.'
				);
				response.end();
			}
        }).listen(IN_PORT);
    
        LOG.warn('Listening for stream on http://'+ SR.Settings.SERVER_INFO.IP +':'+IN_PORT+'/<channel>/<para1>/<para2>/<para3>/...', 'SR.Stream');
        LOG.warn('Awaiting WebSocket connections on ws://' + SR.Settings.SERVER_INFO.IP + ':'+OUT_PORT+'/', 'SR.Stream');
    }
    
    this.stop = function () {

        if (socketServer) {
            socketServer.close();
        }
        
        if (streamServer) {
            streamServer.close();
        }
    }
    
}
606912
function WebSocketFrame(maskBytes, frameHeader, config) {
    this.maskBytes = maskBytes;
    this.frameHeader = frameHeader;
    this.config = config;
    this.maxReceivedFrameSize = config.maxReceivedFrameSize;
    this.protocolError = false;
    this.frameTooLarge = false;
    this.invalidCloseFrameLength = false;
    this.parseState = DECODE_HEADER;
    this.closeStatus = -1;
}
693661
function (ws, message) {
  let clientMessage;

  try {
    clientMessage = JSON.parse(message);
    /* jshint ignore:start */
    if (_.get(clientMessage, 'type') === 'message') {
      ws.send(JSON.stringify({
        ok: true,
        reply_to: _.get(clientMessage, 'id'),
        ts: Date.now(),
        message: _.get(clientMessage, 'text', message),
        type: _.get(clientMessage, 'type', 'message'),
        user: _.get(clientMessage, 'user', 'U1234567'),
        channel: _.get(clientMessage, 'channel', 'C1234567'),
      }));
    }
    /* jshint ignore:end */
  } catch (err) {
    logger.info('Invalid socket data ', message);
  }
}
36279
function () {
        // Ensure that there is no open WebSocket from a previous Connection.
        this._closeSocket();

        // Create the new WobSocket
        this.socket = new WebSocket(this._conn.service, "xmpp");
        this.socket.onopen = this._onOpen.bind(this);
        this.socket.onerror = this._onError.bind(this);
        this.socket.onclose = this._onClose.bind(this);
        this.socket.onmessage = this._connect_cb_wrapper.bind(this);
    }
165911
function connectIfNeeded() {
      // console.log('re-establishing the connect');
      websocket = null;
      socketCreationInProcess = false;

      // The token may have expired so test for it.
      getToken(determineService())
        .then(() => {
          return processSTTSocketStart(false);
        })
        .then(() => {
          //return Promise.resolve();
          return;
        })
        .catch((err) => {
          //return Promise.resolve();
          return;
        });
    }
1293657
def run!(runtime_config = {})
			@websocket_config.merge! runtime_config

			EM.run do
				if @websocket_config[:tick_interval]
					EM.add_periodic_timer(@websocket_config[:tick_interval]) do
						socket_trigger(:on_tick, @socket_connected)
					end
				end

				EventMachine::WebSocket.run(host: @websocket_config[:socket_host], port: @websocket_config[:socket_port]) do |socket|
					@socket_active = socket
					socket.onopen do |handshake|
						@socket_connected = true
						socket_trigger(:on_socket_open, handshake)
					end

					socket.onmessage do |msg| 
						process_message(msg)
					end

					socket.onclose do 
						socket_trigger(:on_socket_close)
						@socket_connected = false 
					end
				end
			 
				Launchy.open("http://#{@websocket_config[:http_host]}:#{@websocket_config[:http_port]}/")
				WebsocketGui::SinatraWrapper.view_path = @websocket_config[:view]
				WebsocketGui::SinatraWrapper.run!(
					port: @websocket_config[:http_port], 
					bind: @websocket_config[:http_host])
			end
		end
271620
async def create_websocket_server(sock, filter=None):  # pylint: disable=W0622
    
    ws = Websocket()
    await ws.start_server(sock, filter=filter)
    return ws
235091
@Override
  public void streamReply(WebSocket session,
                          HeadersAmp headers,
                          String to,
                          long qid,
                          int sequence,
                          List<Object> values,
                          Throwable exn,
                          boolean isComplete)
    throws IOException
  {
    /*
    if (values != null && values.size() > 0) {
      try (Writer out = session.getBasicRemote().getSendWriter()) {
        init(out);
        streamResult(headers, to, qid, values);
      }
    }
    
    if (exn != null) {
      try (Writer out = session.getBasicRemote().getSendWriter()) {
        init(out);
        streamError(headers, to, qid, exn);
      }
    }
    else if (isComplete) {
      try (Writer out = session.getBasicRemote().getSendWriter()) {
        init(out);
        streamComplete(headers, to, qid);
      }
    }
    */
  }
317187
def _publish_queue_wss(self):
        

        msg = []
        for m in self._tx_queue:
            msg.append({'id': m.id, 'body': m.body, 'zone_id': m.zone_id})
        self._ws.send(json.dumps(msg), opcode=websocket.ABNF.OPCODE_BINARY)
1116905
@FFDCIgnore({ LookaheadSuccess.class })
  private boolean jj_2_6(int xla) {
    jj_la = xla; jj_lastpos = jj_scanpos = token;
    try { return !jj_3_6(); }
    catch(LookaheadSuccess ls) { return true; }
    finally { jj_save(5, xla); }
  }
1272783
@Override
	public void processMessage(final WebSocketMessage webSocketData) {

		setDoTransactionNotifications(true);

		final SecurityContext securityContext = getWebSocket().getSecurityContext();

		try {

			final String uuid  = webSocketData.getId();
			int sequenceNumber = webSocketData.getNodeDataIntegerValue("chunkId");
			int chunkSize      = webSocketData.getNodeDataIntegerValue("chunkSize");
			int chunks         = webSocketData.getNodeDataIntegerValue("chunks");
			Object rawData     = webSocketData.getNodeData().get("chunk");

			byte[] data        = new byte[0];

			if (rawData != null) {

				if (rawData instanceof String) {

					logger.debug("Raw data: {}", rawData);

//                                        data = Base64.decodeBase64(((String)rawData).getBytes("UTF-8"));
					data = Base64.decode(((String) rawData));

					logger.debug("Decoded data: {}", data);

				}

			}

			final File file = (File) getNode(uuid);
			if (file.isTemplate()) {

				logger.warn("No write permission, file is in template mode: {}", new Object[] {file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission, file is in template mode").code(400).build(), true);
				return;

			}

			if (!file.isGranted(Permission.write, securityContext)) {

				logger.warn("No write permission for {} on {}", new Object[] {getWebSocket().getCurrentUser().toString(), file.toString()});
				getWebSocket().send(MessageBuilder.status().message("No write permission").code(400).build(), true);
				return;

			}

			getWebSocket().handleFileChunk(uuid, sequenceNumber, chunkSize, data, chunks);

			if (sequenceNumber+1 == chunks) {

				FileHelper.updateMetadata(file);

				file.increaseVersion();

				getWebSocket().removeFileUploadHandler(uuid);

				logger.debug("File upload finished. Checksum: {}, size: {}", new Object[]{ file.getChecksum(), file.getSize() });

			}

			final long currentSize = (long)(sequenceNumber * chunkSize) + data.length;

			// This should trigger setting of lastModifiedDate in any case
			getWebSocket().send(MessageBuilder.status().code(200).message("{\"id\":\"" + file.getUuid() + "\", \"name\":\"" + file.getName() + "\",\"size\":" + currentSize + "}").build(), true);

		} catch (IOException | FrameworkException ex) {

			String msg = ex.toString();

			// return error message
			getWebSocket().send(MessageBuilder.status().code(400).message("Could not process chunk data: ".concat((msg != null)
				? msg
				: "")).build(), true);
		}
	}
521466
function (url) {
            var self = this;
            this._ws = new WebSocket(url);

            // One potential source of confusion: the transport sends two "types" of messages -
            // these are distinct from the protocol's own messages. This is because this transport
            // needs to send an initial "connect" message telling the Brackets side of the transport
            // the URL of the page that it's connecting from, distinct from the actual protocol
            // message traffic. Actual protocol messages are sent as a JSON payload in a message of
            // type "message".
            //
            // Other transports might not need to do this - for example, a transport that simply
            // talks to an iframe within the same process already knows what URL that iframe is
            // pointing to, so the only comunication that needs to happen via postMessage() is the
            // actual protocol message strings, and no extra wrapping is necessary.

            this._ws.onopen = function (event) {
                // Send the initial "connect" message to tell the other end what URL we're from.
                self._ws.send(JSON.stringify({
                    type: "connect",
                    url: global.location.href
                }));
                console.log("[Brackets LiveDev] Connected to Brackets at " + url);
                if (self._callbacks && self._callbacks.connect) {
                    self._callbacks.connect();
                }
            };
            this._ws.onmessage = function (event) {
                console.log("[Brackets LiveDev] Got message: " + event.data);
                if (self._callbacks && self._callbacks.message) {
                    self._callbacks.message(event.data);
                }
            };
            this._ws.onclose = function (event) {
                self._ws = null;
                if (self._callbacks && self._callbacks.close) {
                    self._callbacks.close();
                }
            };
            // TODO: onerror
        }
543465
async def create_websocket(url: str,
                           ssl: Optional[SSLContext] = None,
                           headers: Optional[list] = None,
                           subprotocols: Optional[list] = None):
    
    url = yarl.URL(url)
    args = {}
    if headers:
        args["headers"] = headers

    # automatically use ssl if it's websocket secure
    if ssl is None:
        ssl = url.scheme == "wss"
    if ssl:
        if ssl is True:
            ssl = SSLContext()
        args["ssl_context"] = ssl
        args["autostart_tls"] = True
        args["tls_standard_compatible"] = False

    addr = (url.host, int(url.port))
    ws = Websocket()
    await ws.__ainit__(
        addr=addr, path=url.path_qs, subprotocols=subprotocols, **args)
    return ws
1050590
function ws_send(socket, data) {
	//console.log("send: " + data);
	let header;
	let payload = new Buffer.from(data);
	const len = payload.length;
	
	if (len <= 125) {
		header = new Buffer.alloc(2);
		header[1] = len;
	} else if (len <= 0xffff) {
		header = new Buffer.alloc(4);
		header[1] = 126;
		header[2] = (len >> 8) & 0xff;
		header[3] = len & 0xff;
	} else { /* 0xffff < len <= 2^63 */
		header = new Buffer(10);
		header[1] = 127;
		header[2] = (len >> 56) & 0xff;
		header[3] = (len >> 48) & 0xff;
		header[4] = (len >> 40) & 0xff;
		header[5] = (len >> 32) & 0xff;
		header[6] = (len >> 24) & 0xff;
		header[7] = (len >> 16) & 0xff;
		header[8] = (len >> 8) & 0xff;
		header[9] = len & 0xff;
	}
	
	header[0] = 0x81;
	socket.write(Buffer.concat([header, payload],
		 header.length + payload.length), 'binary');
	//console.log('sent ' + data.length + ' bytes');
}
258248
function socketOnEnd() {
  const websocket = this[kWebSocket];

  websocket.readyState = WebSocket.CLOSING;
  websocket._receiver.end();
  this.end();
}