Create server multicast socket. Socket will be joined to the multicast-group (same as it is
		specified in client configuration, same as client does)

		:param config: server configuration
		:return: socket.socket
501460
def create_server_socket(self, config):
		
		server_socket = WUDPNetworkNativeTransport.create_server_socket(self, config)

		group = socket.inet_aton(str(self.target_socket(config).address()))
		group_membership = struct.pack('4sL', group, socket.INADDR_ANY)
		server_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, group_membership)
		return server_socket
444018
protected RequestConfig createConfig() {
    if (proxy == null && socketTimeout < 0 && connectTimeout < 0) {
      return null;
    }
    Builder builder = RequestConfig.custom();
    if (proxy != null) {
      builder.setProxy(proxy);
    }
    if (socketTimeout >= 0) {
      builder.setSocketTimeout(socketTimeout);
    }
    if (connectTimeout >= 0) {
      builder.setConnectTimeout(connectTimeout);
    }
    return builder.build();
  }
1308054
function CBSocketWrapper(config) {

    this.config = config;

    var self = this;

    // Connection status flag
    this.connected = false;

    // Socket Wrapper listeners
    this.on('connect', function() {
        self.connected = true;
        logger.info('Connected to Continuum Bridge', self.config.cbSocket);
    });
    this.on('connecting', function() {
        self.connected = false;
        logger.info('Connecting..');
    });
    this.on('error', function(error) {
        self.connected = false;
        logger.log('Error', error);
    });
    this.on('disconnect', function() {
        self.connected = false;
        logger.info('Disconnected from Continuum Bridge:', self.config.cbSocket);
    });
}
1096158
def close_client_socket(self, config, close_fd=True):
		
		if close_fd is True:
			self.__client_socket.close()
		self.__client_socket = None
530055
def new_connection (self):
        
        if self.get('LocalSocket'):
            host = 'localhost'
            sock = self.create_local_socket()
        elif self.get('TCPSocket'):
            host = self.get('TCPAddr', 'localhost')
            sock = self.create_tcp_socket(host)
        else:
            raise ClamavError(_("one of TCPSocket or LocalSocket must be enabled"))
        return sock, host
959890
def _init_multicast_socket(self):
        
        self.debug("()")
        # Create a UDP socket
        self._multicast_socket = socket.socket(
            socket.AF_INET,
            socket.SOCK_DGRAM
        )

        # Allow reuse of addresses
        self._multicast_socket.setsockopt(
            socket.SOL_SOCKET,
            socket.SO_REUSEADDR,
            1
        )

        # Set multicast interface to local_ip
        self._multicast_socket.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_IF,
            socket.inet_aton(self._multicast_ip)
        )

        # Set multicast time-to-live
        # Should keep our multicast packets from escaping the local network
        self._multicast_socket.setsockopt(
            socket.IPPROTO_IP,
            socket.IP_MULTICAST_TTL,
            self._multicast_ttl
        )

        self._add_membership_multicast_socket()
        # Bind socket
        if platform.system().lower() == "darwin":
            self._multicast_socket.bind(("0.0.0.0", self._multicast_bind_port))
        else:
            self._multicast_socket.bind(
                (self._multicast_ip, self._multicast_bind_port)
            )
        self._listening.append(self._multicast_socket)
44366
private void openAndBindSocket() {
    try {
      this.clientSocket = new MulticastSocket();
      Utils.selectAppropriateInterface(clientSocket);
      this.clientSocket.joinGroup(SsdpParams.getSsdpMulticastAddress());
    } catch (IOException e) {
      callback.onFailed(e);
    }
  }
1167755
function Client(arg, port) {
  if (this instanceof Client === false) {
    return new Client(arg, port);
  }

  if (arg === undefined) {
    throw new TypeError('arg should be a host address, name or universe');
  }

  this.host = Number.isInteger(arg) ? e131.getMulticastGroup(arg) : arg;
  this.port = port || e131.DEFAULT_PORT;
  this._socket = dgram.createSocket('udp4');
}
597865
def subscriberSocket(self, host, port, filt=b'', conflate=False):
        '''
        
        '''
        socket = self._context.socket(zmq.SUB)
        if conflate:
            socket.setsockopt(zmq.CONFLATE, 1)

        socket.connect(self.tcpAddress(host, port))
        socket.setsockopt(zmq.SUBSCRIBE, filt)
        return socket
402011
def socket(self):
        '''
        
        '''
        if not hasattr(self, '_socket'):
            # create a new one
            self._socket = self.context.socket(zmq.REQ)
            if hasattr(zmq, 'RECONNECT_IVL_MAX'):
                self._socket.setsockopt(
                    zmq.RECONNECT_IVL_MAX, 5000
                )

            self._set_tcp_keepalive()
            if self.master.startswith('tcp://['):
                # Hint PF type if bracket enclosed IPv6 address
                if hasattr(zmq, 'IPV6'):
                    self._socket.setsockopt(zmq.IPV6, 1)
                elif hasattr(zmq, 'IPV4ONLY'):
                    self._socket.setsockopt(zmq.IPV4ONLY, 0)
            self._socket.linger = self.linger
            if self.id_:
                self._socket.setsockopt(zmq.IDENTITY, self.id_)
            self._socket.connect(self.master)
        return self._socket
939976
public Socket createSocket(SocketType type)
    {
        // Create and register socket
        Socket socket = context.socket(type);
        socket.setRcvHWM(this.rcvhwm);
        socket.setSndHWM(this.sndhwm);
        sockets.add(socket);
        return socket;
    }
483633
protected synchronized ServerSocket initServerSocket() throws IOException, RetryableChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "ServerSocket called, new ServerSocket needs to be created");
        }
        TCPChannelConfiguration channelConfig = tcpChannel.getConfig();

        IOException bindError = null;
        BindInfo earlyBind = portBoundEarly(channelConfig.getPort());

        if (earlyBind == null) {
            InetSocketAddress socketAddress = null;

            if (channelConfig.getHostname() == null) {
                socketAddress = new InetSocketAddress((InetAddress) null, channelConfig.getPort());
            } else {
                socketAddress = new InetSocketAddress(channelConfig.getHostname(), channelConfig.getPort());
            }

            if (!socketAddress.isUnresolved()) {
                serverSocket = openServerSocket();

                // receieve buffer size for accepted sockets is set on serverSocket,
                // send buffer size is set on individual sockets

                if ((channelConfig.getReceiveBufferSize() >= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MIN)
                    && (channelConfig.getReceiveBufferSize() <= TCPConfigConstants.RECEIVE_BUFFER_SIZE_MAX)) {
                    serverSocket.setReceiveBufferSize(channelConfig.getReceiveBufferSize());
                }
                if (!channelConfig.getSoReuseAddress()) {
                    //Forced re-use==false custom property
                    try {
                        attemptSocketBind(socketAddress, false);
                    } catch (IOException e) {
                        // no FFDC
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Forced re-use==false bind attempt failed, ioe=" + e);
                        }
                        bindError = e;
                    }
                } else {
                    //re-use==true (default)
                    // try the standard startup attempts
                    try {
                        attemptSocketBind(socketAddress, false);
                        //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                        //for future binds.
                        if (!TCPFactoryConfiguration.isWindows()) {
                            this.serverSocket.setReuseAddress(true);
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                            }
                        }
                    } catch (IOException ioe) {
                        // See if we got the error because the port is in waiting to be cleaned up.
                        // If so, no one should be accepting connections on it, and open should fail.
                        // If that's the case, we can set ReuseAddr to expedite the bind process.
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                        }
                        bindError = ioe;
                        try {
                            String hostName = channelConfig.getHostname();
                            if (hostName == null) {
                                hostName = "localhost";
                            }
                            InetSocketAddress testAddr = new InetSocketAddress(hostName, channelConfig.getPort());
                            // PK40741 - test for localhost being resolvable before using it
                            if (!testAddr.isUnresolved()) {
                                SocketChannel testChannel = SocketChannel.open(testAddr);
                                // if we get here, socket opened successfully, which means
                                // someone is really listening
                                // so close connection and don't bother trying to bind again
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "attempt to connect to port to check listen status worked, someone else is using the port!");
                                }
                                testChannel.close();
                            } else {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                                }
                            }
                        } catch (IOException testioe) {
                            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                Tr.debug(tc, "attempt to connect to port to check listen status failed with IOException: " + testioe.getMessage());
                            }
                            try {
                                // open (or close) got IOException, retry with reuseAddr on
                                attemptSocketBind(socketAddress, true);
                                bindError = null;

                            } catch (IOException newioe) {
                                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                                    Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                                }
                                bindError = newioe;
                            }
                        }
                    }
                }

                if (bindError == null) {
                    // listen port can be different than config port if configed port is '0'
                    listenPort = serverSocket.getLocalPort();
                } else {
                    String displayableHostName = channelConfig.getDisplayableHostname();

                    // add in the exception message to help in problem diagnostics without tracing
                    Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                             new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()),
                                            bindError.getMessage() });

                    throw new RetryableChannelException(bindError.getMessage());
                }

            } else { // unresolved socket address
                String displayableHostName = channelConfig.getDisplayableHostname();
                Tr.error(tc, TCPChannelMessageConstants.LOCAL_HOST_UNRESOLVED,
                         new Object[] { channelConfig.getChannelData().getExternalName(), displayableHostName, String.valueOf(channelConfig.getPort()) });

                throw new RetryableChannelException(new IOException("local address unresolved"));
            }

        } else {
            // this port was bound earlier by a different service
            Exception e = earlyBind.getBindException();
            if (e == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Found early bind, setting serverSocket and listenPort");
                }

                serverSocket = earlyBind.getServerSocket();
                // listen port can be different than config port if configed port is '0'
                listenPort = serverSocket.getLocalPort();
            } else {

                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Early Bind generated the following exception: " + e);
                }

                // add in the exception message to help in problem diagnostics without tracing
                Tr.error(tc, TCPChannelMessageConstants.BIND_ERROR,
                         new Object[] { channelConfig.getChannelData().getExternalName(), earlyBind.getHostname(), String.valueOf(earlyBind.getPort()), e.getMessage() });

                if (e instanceof IOException) {
                    throw (IOException) e;
                }
                if (e instanceof RetryableChannelException) {
                    throw (RetryableChannelException) e;
                }
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "new ServerSocket successfully created");
        }

        return this.serverSocket;
    }
690693
def _create_server(host, port):
    

    exc = socket.error("getaddrinfo returns an empty list")
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            # Create the listening socket
            sock = socket.socket(af, socktype, proto)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(sa)
            sock.listen(1024)
            return sock

        except socket.error as exc:
            # Clean up after ourselves
            if sock is not None:
                sock.close()

    # Couldn't create a listening socket
    raise exc
287658
private static Group configureCommandLine() {
        DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
        ArgumentBuilder aBuilder = new ArgumentBuilder();
        GroupBuilder gBuilder = new GroupBuilder();

        DefaultOption nosslOption = oBuilder.withLongName("nossl").withShortName("n").withDescription("Do no use SSL").create();

        DefaultOption weakSslOption = oBuilder.withLongName("weakCiherSuites").withShortName("w").withDescription("Enable weak cipher suites").create();
        
        DefaultOption unknownOption = oBuilder.withLongName("unknown").withShortName("u")
                .withDescription("Make socket timeouts return an UNKNOWN state instead of CRITICAL").create();

        DefaultOption hostOption = oBuilder.withLongName("host").withShortName("H")
                .withDescription("The address of the host running the JNRPE/NRPE daemon")
                .withArgument(aBuilder.withName("host").withMinimum(1).withMaximum(1).create()).create();

        NumberValidator positiveInt = NumberValidator.getIntegerInstance();
        positiveInt.setMinimum(0);
        DefaultOption portOption = oBuilder
                .withLongName("port")
                .withShortName("p")
                .withDescription("The port on which the daemon is running (default=5666)")
                .withArgument(
                        aBuilder.withName("port").withMinimum(1).withMaximum(1).withDefault(Long.valueOf(DEFAULT_PORT)).withValidator(positiveInt)
                                .create()).create();

        DefaultOption timeoutOption = oBuilder
                .withLongName("timeout")
                .withShortName("t")
                .withDescription("Number of seconds before connection times out (default=10)")
                .withArgument(
                        aBuilder.withName("timeout").withMinimum(1).withMaximum(1).withDefault(Long.valueOf(DEFAULT_TIMEOUT))
                                .withValidator(positiveInt).create()).create();

        DefaultOption commandOption = oBuilder
                    .withLongName("command")
                    .withShortName("c")
                    .withDescription("The name of the command that the remote daemon should run")
                    .withArgument(
                            aBuilder
                                .withName("command")
                                .withMinimum(1)
                                .withMaximum(1).create()
                                )
                                .create();

        DefaultOption argsOption = oBuilder
                .withLongName("arglist")
                .withShortName("a")
                .withDescription(
                        "Optional arguments that should be passed to the command.  Multiple arguments should be separated by "
                                + "a space (' '). If provided, this must be the last option supplied on the command line.")
                .withArgument(aBuilder.withName("arglist").withMinimum(1).create()).create();

        DefaultOption helpOption = oBuilder.withLongName("help").withShortName("h").withDescription("Shows this help").create();

        Group executionOption = gBuilder
                                    .withOption(nosslOption)
                                    .withOption(weakSslOption)
                                    .withOption(unknownOption)
                                    .withOption(hostOption)
                                    .withOption(portOption)
                                    .withOption(timeoutOption)
                                    .withOption(commandOption)
                                    .withOption(argsOption).create();

        return gBuilder.withOption(executionOption).withOption(helpOption).withMinimum(1).withMaximum(1).create();
    }
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();
        }
    }
    
}
46265
def client(cls, config):
        
        if not hasattr(cls, "_client"):
            cls._client = statsd.StatsClient(config.STATSD_HOST, config.STATSD_PORT, config.STATSD_PREFIX)
        return cls._client
24342
function Socket(config) {
    var host = config.host || '127.0.0.1',
        port = config.port || 8880,
        maxsize = config.maxsize || MAXSIZE,
        encoding = config.encoding || 'utf8',
        callback = config.callback,
        broadcast = config.broadcast || true;

    var clientList = [];

    var server = net.createServer(function(socket) {
        utils.log('[socket connected successfully]: ', socket.remoteAddress + ':' + socket.remotePort);
        
        clientList.push(socket);

        socket.setEncoding(encoding);

        socket.on('lookup', function() {
            utils.log('[create socket]');
        });

        socket.on('connect', function(sock) {
            utils.log('[socket connected successfully]: ', sock.remoteAddress + ':' + sock.remotePort);
        });

        socket.on('data', function(data) {
            //data = socket.remoteAddress + '|' + socket.remotePort + ':\n' + data;
            //utils.log('socket get data:\n', data);

            callback && callback(data, socket);

            // broadcast && socket.write(data, function() {
            //     utils.log('[socket broadcast one data]');
            // });

            if(broadcast){
                utils.log('[socket broadcast one data]');
                for(var i in clientList){
                    var sock = clientList[i];
                    //不广播给自己
                    (sock !== socket) && (function(sock, data){
                        var dataFrom = socket.remoteAddress + ':' + socket.remotePort;// + ':\n' + data
                        sock.write(dataFrom + ':\n' + data, function() {
                            var dataTo = sock.remoteAddress + ':' + sock.remotePort;
                            utils.log('[' + dataFrom + ' send a message to ' + dataTo + ']:\n', data);
                        });
                    })(sock, data);
                }
            }
            //socket.end();
        });

        socket.on('end', function() {
            console.log('end');
        });

        socket.on('drain', function() {
            console.log('drain');
        });

        socket.on('error', function(err) {
            console.log('[socket error]: ', err)
        });

        socket.on('close', function() {
            clientList.splice(clientList.indexOf(socket), 1);
            socket.destroy();
            console.log('[client closed]');

        });

        socket.write('hello\r\n');
        //socket.pipe(socket);
        //console.log(socket);
    })
    .listen(port, host, function() { //'listening' listener
        console.log('server bound: ', host, ':', port);
    })
    .on('connection', function(){
        console.log('[new socket connection], count: ', clientList.length);
    })
    .on('error', function(err){
        console.log('[server error]:', err);
        if (err.code == 'EADDRINUSE') {
            console.log('Address in use, retrying...');
            setTimeout(function() {
                server.close();
                server.listen(PORT, HOST);
            }, 1000);
        }
    })
    .on('close', function(){
        console.log('[server closed]');
    })
}