// NewSocketServer constructs a new SocketServer, registering handlers for the
// "connection", "disconnection", and "subscribe" events.
558145
func NewSocketServer(newTxChan chan *NewTx, params *chaincfg.Params) (*SocketServer, error) {
	server, err := socketio.NewServer(nil)
	if err != nil {
		apiLog.Errorf("Could not create socket.io server: %v", err)
		return nil, err
	}

	// Each address subscription uses its own room, which has the same name as
	// the address. The number of subscribers for each room is tracked.
	addrs := roomSubscriptionCounter{
		RWMutex: new(sync.RWMutex),
		c:       make(map[string]int),
	}

	server.On("connection", func(so socketio.Socket) {
		apiLog.Debug("New socket.io connection")
		// New connections automatically join the inv and sync rooms.
		so.Join("inv")
		so.Join("sync")

		// Disconnection decrements or deletes the subscriber counter for each
		// address room to which the client was subscribed.
		so.On("disconnection", func() {
			apiLog.Debug("socket.io client disconnected")
			addrs.Lock()
			for _, str := range so.Rooms() {
				if c, ok := addrs.c[str]; ok {
					if c == 1 {
						delete(addrs.c, str)
					} else {
						addrs.c[str]--
					}
				}
			}
			addrs.Unlock()
		})

		// Subscription to a room checks the room name is as expected for an
		// address (TODO: do this better), joins the room, and increments the
		// room's subscriber count.
		so.On("subscribe", func(room string) {
			if len(room) > 64 || !isAlphaNumeric(room) {
				return
			}
			if addr, err := dcrutil.DecodeAddress(room); err == nil {
				if addr.IsForNet(params) {
					so.Join(room)
					apiLog.Debugf("socket.io client joining room: %s", room)

					addrs.Lock()
					addrs.c[room]++
					addrs.Unlock()
				}
			}
		})
	})

	server.On("error", func(_ socketio.Socket, err error) {
		apiLog.Errorf("Insight socket.io server error: %v", err)
	})

	sockServ := SocketServer{
		Server:           *server,
		params:           params,
		watchedAddresses: addrs,
	}
	go sockServ.sendNewTx(newTxChan)
	return &sockServ, nil
}
1323199
func newSocket(server *Server, bs backend.BackendSocket) *Socket {
	// Create a new socket value.
	s := &Socket{
		server: server,
		bs:     bs,

		id:       utils.RandomString(socketIDLength),
		channels: newChannels(),

		writeChan:    bs.WriteChan(),
		readChan:     bs.ReadChan(),
		isClosedChan: bs.ClosedChan(),

		pingTimer:   time.NewTimer(pingPeriod),
		pingTimeout: time.NewTimer(pingResponseTimeout),
	}

	// Create the main channel.
	s.mainChannel = s.Channel(mainChannelName)

	// Call the on close method as soon as the socket closes.
	go func() {
		<-s.isClosedChan
		s.onClose()
	}()

	// Stop the timeout again. It will be started by the ping timer.
	s.pingTimeout.Stop()

	// Add the new socket to the active sockets map.
	// If the ID is already present, then generate a new one.
	func() {
		// Lock the mutex.
		s.server.socketsMutex.Lock()
		defer s.server.socketsMutex.Unlock()

		// Be sure that the ID is unique.
		for {
			if _, ok := s.server.sockets[s.id]; !ok {
				break
			}

			s.id = utils.RandomString(socketIDLength)
		}

		// Add the socket to the map.
		s.server.sockets[s.id] = s
	}()

	// Start the loops and handlers in new goroutines.
	go s.pingTimeoutHandler()
	go s.readLoop()
	go s.pingLoop()

	return s
}
1365429
func newSocketConnection(cfg *socketConfig) (websocketFeed, error) {
	dialer := &websocket.Dialer{
		Proxy:            http.ProxyFromEnvironment, // Same as DefaultDialer.
		HandshakeTimeout: 10 * time.Second,          // DefaultDialer is 45 seconds.
	}

	conn, _, err := dialer.Dial(cfg.address, nil)
	if err != nil {
		return nil, err
	}
	return &socketClient{
		conn: conn,
		done: make(chan struct{}),
	}, nil
}
677030
func NewServer() *Server {
	return &Server{serviceMap: make(map[string]*service), contextType: reflect.TypeOf("")}
}
882699
func NewServer(ctx context.Context, c Config) (*Server, error) {
	return newServer(ctx, c, defaultRotationStrategy(
		value(c.RotateKeysAfter, 6*time.Hour),
		value(c.IDTokensValidFor, 24*time.Hour),
	))
}
934025
func NewServer(r *multichannel.Registrar, metricsProvider metrics.Provider, debug *localconfig.Debug, timeWindow time.Duration, mutualTLS bool) ab.AtomicBroadcastServer {
	s := &server{
		dh: deliver.NewHandler(deliverSupport{Registrar: r}, timeWindow, mutualTLS, deliver.NewMetrics(metricsProvider)),
		bh: &broadcast.Handler{
			SupportRegistrar: broadcastSupport{Registrar: r},
			Metrics:          broadcast.NewMetrics(metricsProvider),
		},
		debug:     debug,
		Registrar: r,
	}
	return s
}
589831
func NewServer(hostname string, recorder record.EventRecorder, listener Listener, httpServerFactory HTTPServerFactory) Server {
	if listener == nil {
		listener = stdNetListener{}
	}
	if httpServerFactory == nil {
		httpServerFactory = stdHTTPServerFactory{}
	}
	return &server{
		hostname:    hostname,
		recorder:    recorder,
		listener:    listener,
		httpFactory: httpServerFactory,
		services:    map[types.NamespacedName]*hcInstance{},
	}
}
1331704
func NewServer(bindHost string, bindPort int, syslogishServer *syslogish.Server) (*Server, error) {
	return &Server{
		bindHost: bindHost,
		bindPort: bindPort,
		handler:  &requestHandler{syslogishServer: syslogishServer},
	}, nil
}
1294962
func NewServer(config Config) (*Server, error) {
	server := &Server{
		startTime:    time.Now(),
		Config:       config,
		tcpServers:   []*healthApi.Server{},
		connectivity: &healthReport{},
	}

	swaggerSpec, err := loads.Analyzed(healthApi.SwaggerJSON, "")
	if err != nil {
		return nil, err
	}

	if !config.Passive {
		cl, err := ciliumPkg.NewClient(config.CiliumURI)
		if err != nil {
			return nil, err
		}

		server.Client = cl
		server.Server = *server.newServer(swaggerSpec, 0)
	}
	for port := range PortToPaths {
		srv := server.newServer(swaggerSpec, port)
		server.tcpServers = append(server.tcpServers, srv)
	}

	return server, nil
}
11544
func NewServer(codec ServerCodec, defaultHandler interface{}) *Server {
	value := reflect.ValueOf(defaultHandler)
	if !validHandler(value, reflect.TypeOf(defaultHandler).Name()) {
		panic("NewServer: invalid default handler")
	}

	s := &Server{
		closed:  new(int32),
		rooms:   make(map[string]([]*Client)),
		roomsMu: new(sync.RWMutex),

		//Maps socket ID -> list of rooms the client is in
		joinedRooms:   make(map[string][]string),
		joinedRoomsMu: new(sync.RWMutex),

		handlers:     make(map[string]*regMethod),
		handlersLock: new(sync.RWMutex),

		codec:          codec,
		defaultHandler: &regMethod{value, value.Type().In(1)},

		reqMu:   new(sync.Mutex),
		replyMu: new(sync.Mutex),

		Requests: new(sync.WaitGroup),
		clients:  new(int64),
	}

	return s
}
276486
func newSocket(ws *websocket.Conn) *Socket {
	w := &Socket{
		ws:        ws,
		writeChan: make(chan string, global.WriteChanSize),
		readChan:  make(chan string, global.ReadChanSize),
	}

	// Set the closer function.
	w.closer = closer.New(func() {
		// Send a close message to the client.
		// Ignore errors.
		w.write(websocket.CloseMessage, []byte{})

		// Close the socket.
		w.ws.Close()
	})

	return w
}
643483
func newServerConn(conn net.Conn, listener *Listener) *Conn {
	c := &Conn{
		conn:     conn,
		listener: listener,
		closed:   sync2.NewAtomicBool(false),
	}
	if listener.connReadBufferSize > 0 {
		c.bufferedReader = bufio.NewReaderSize(conn, listener.connReadBufferSize)
	}
	return c
}
58443
func NewSocket(path string) (s *Socket, err error) {
	s = &Socket{path: path}
	if err = openSocket(s); err != nil {
		err = fmt.Errorf("open socket: %s", err)
		s.err = err
		return
	}
	return
}
978050
func NewServer(getCmd CmdGetter, socketPath string) (*Server, error) {
	server := rpc.NewServer()
	if err := server.Register(&Jujuc{getCmd: getCmd}); err != nil {
		return nil, err
	}
	listener, err := sockets.Listen(socketPath)
	if err != nil {
		return nil, errors.Annotate(err, "listening to jujuc socket")
	}
	s := &Server{
		socketPath: socketPath,
		listener:   listener,
		server:     server,
		closed:     make(chan bool),
		closing:    make(chan bool),
	}
	return s, nil
}
81097
func NewServer(ctx context.Context, c conn, addrs []tcpip.Address, cfg Config) (*Server, error) {
	if cfg.ServerAddress == "" {
		return nil, fmt.Errorf("dhcp: server requires explicit server address")
	}
	s := &Server{
		conn:    c,
		addrs:   addrs,
		cfg:     cfg,
		cfgopts: cfg.encode(),
		broadcast: tcpip.FullAddress{
			Addr: "\xff\xff\xff\xff",
			Port: ClientPort,
		},

		handlers: make([]chan header, 8),
		leases:   make(map[tcpip.LinkAddress]serverLease),
	}

	for i := 0; i < len(s.handlers); i++ {
		ch := make(chan header, 8)
		s.handlers[i] = ch
		go s.handler(ctx, ch)
	}

	go s.expirer(ctx)
	go s.reader(ctx)
	return s, nil
}
317256
func NewServer(
	host HostInterface,
	resourceAnalyzer stats.ResourceAnalyzer,
	auth AuthInterface,
	enableDebuggingHandlers,
	enableContentionProfiling,
	redirectContainerStreaming bool,
	criHandler http.Handler) Server {
	server := Server{
		host:                       host,
		resourceAnalyzer:           resourceAnalyzer,
		auth:                       auth,
		restfulCont:                &filteringContainer{Container: restful.NewContainer()},
		redirectContainerStreaming: redirectContainerStreaming,
	}
	if auth != nil {
		server.InstallAuthFilter()
	}
	server.InstallDefaultHandlers()
	if enableDebuggingHandlers {
		server.InstallDebuggingHandlers(criHandler)
		if enableContentionProfiling {
			goruntime.SetBlockProfileRate(1)
		}
	} else {
		server.InstallDebuggingDisabledHandlers()
	}
	return server
}
1204336
func NewServerConnection(conn net.Conn, newStreamHandler httpstream.NewStreamHandler) (httpstream.Connection, error) {
	spdyConn, err := spdystream.NewConnection(conn, true)
	if err != nil {
		defer conn.Close()
		return nil, err
	}

	return newConnection(spdyConn, newStreamHandler), nil
}