// Dispatch processes the connection.
172796
func (d *dispatcher) Dispatch(g grim.GrimReaper, conn net.Conn) {

	// Create buffer and read connection type
	buf := make([]byte, 1)
	if _, err := conn.Read(buf); err != nil {
		d.logger.Warn("error reading StreamType",
			"remote", conn.RemoteAddr().String, "err", err)
		conn.Close()
		return
	}

	// Dispatch connection based on first byte
	ctype := StreamType(buf[0])
	if handler, ok := d.handlers[ctype]; ok {
		g.SpawnFunc(func(c context.Context) {
			handler.Handle(c, conn)
		})
		return
	}

	// Process unknown streams if there is an unknown stream handler
	if d.unknown != nil {
		g.SpawnFunc(func(c context.Context) {
			d.unknown.Handle(c, conn)
		})
		return
	}

	// If there is not an unknown stream handler, close the stream.
	d.logger.Warn("closing connection: unknown stream type",
		"type", ctype, "remote", conn.RemoteAddr().String())
	conn.Close()
}
1079071
func (c *Connection) Call(arguments ...interface{}) (interface{}, error) {
	c.lock.Lock()
	c.lastRequest++
	id := c.lastRequest
	resultChannel := make(chan *commandResult)
	c.waitingRequests[id] = resultChannel
	c.lock.Unlock()

	defer func() {
		c.lock.Lock()
		close(c.waitingRequests[id])
		delete(c.waitingRequests, id)
		c.lock.Unlock()
	}()

	err := c.sendCommand(id, arguments...)
	if err != nil {
		return nil, err
	}

	result := <-resultChannel
	if result.Status == "success" {
		return result.Data, nil
	}
	return nil, fmt.Errorf("mpv error: %s", result.Status)
}
339938
func DispatchStreamHandler(
	h StreamHandler,
	stream *ServerStream,
) (err error) {
	return InvokeStreamHandler(StreamInvokeRequest{
		Stream:  stream,
		Handler: h,
	})
}
1144182
func (e *endpoint) Attach(dispatcher stack.NetworkDispatcher) {
	e.dispatcher = dispatcher
	e.lower.Attach(e)
}
785261
func (kea *KamEvapi) dispatchEvent(dataIn []byte) {
	matched := false
	for matcher, handlers := range kea.eventHandlers {
		if matcher.Match(dataIn) {
			matched = true
			for _, f := range handlers {
				go f(dataIn, kea.connId)
			}
		}
	}
	if !matched {
		kea.logger.Printf(fmt.Sprintf("WARNING: No handler for inbound data: %s", dataIn))
	}
}
742768
func (t *FixedInterval) Register(callback events.Callback) {
	t.Dispatcher.Register(t.etype, callback)
}
692730
func (c *Comm) DispatchConsensus(ctx context.Context, request *orderer.ConsensusRequest) error {
	reqCtx, err := c.requestContext(ctx, request)
	if err != nil {
		return err
	}
	return c.H.OnConsensus(reqCtx.channel, reqCtx.sender, request)
}
1194315
func (s *Server) Dispatch(packet []byte) ([]byte, error) {
	req := &Packet{}

	err := req.UnmarshalBinary(packet)
	if err != nil {
		return nil, err
	}

	if Trace {
		fmt.Fprintf(os.Stderr, "[hgfs] request  %#v\n", req.Header)
	}

	var res interface{}

	handler, ok := s.handlers[req.Op]
	if ok {
		res, err = handler(req)
	} else {
		err = &Status{
			Code: StatusOperationNotSupported,
			Err:  fmt.Errorf("unsupported Op(%d)", req.Op),
		}
	}

	return req.Reply(res, err)
}
69739
func (dc *DispatcherClient) Send(funcName string, request interface{}) error {
	req := dc.getRequest(funcName, request)
	return dc.c.Send(req)
}
181941
func (d *Dispatcher) handler(payload proto.Message) (handler, error) {
	name := proto.MessageName(payload)

	d.mu.RLock()
	defer d.mu.RUnlock()

	handler, registered := d.handlers[name]
	if !registered {
		return handler, fmt.Errorf("handler for %q is not registered", name)
	}
	return handler, nil
}
723567
func DispatchOnewayHandler(
	ctx context.Context,
	h OnewayHandler,
	req *Request,
) (err error) {
	return InvokeOnewayHandler(OnewayInvokeRequest{
		Context: ctx,
		Request: req,
		Handler: h,
	})
}
680765
func dispatchAdd(d dispatchRequest, c *instructions.AddCommand) error {
	downloader := newRemoteSourceDownloader(d.builder.Output, d.builder.Stdout)
	copier := copierFromDispatchRequest(d, downloader, nil)
	defer copier.Cleanup()

	copyInstruction, err := copier.createCopyInstruction(c.SourcesAndDest, "ADD")
	if err != nil {
		return err
	}
	copyInstruction.chownStr = c.Chown
	copyInstruction.allowLocalDecompression = true

	return d.builder.performCopy(d, copyInstruction)
}
926184
func Dispatch(ev interface{}) {
	listenersMutex.RLock()
	defer listenersMutex.RUnlock()

	evType := reflect.TypeOf(ev)
	vals := []reflect.Value{reflect.ValueOf(ev)}

	// call listeners for the actual static type
	callListeners(evType, vals)

	// also check if the type implements any of the registered interfaces
	for _, in := range interfaces {
		if evType.Implements(in) {
			callListeners(in, vals)
		}
	}
}
1312051
func (c *Client) OnConnect(handler func()) {
	c.m.Lock()
	c.onConnectHandlers = append(c.onConnectHandlers, handler)
	c.m.Unlock()
}
222311
func (service *Service) Dispatch(msg []string) {

	if len(msg) > 0 {
		//  Queue message if any
		service.requests = append(service.requests, msg)
	}

	service.broker.Purge()
	for len(service.waiting) > 0 && len(service.requests) > 0 {
		var worker *Worker
		worker, service.waiting = popWorker(service.waiting)
		service.broker.waiting = delWorker(service.broker.waiting, worker)
		msg, service.requests = popMsg(service.requests)
		worker.Send(mdapi.MDPW_REQUEST, "", msg)
	}
}
291736
func (cc *clientConn) dispatch(ctx context.Context, data []byte) error {
	span := opentracing.StartSpan("server.dispatch")
	ctx = opentracing.ContextWithSpan(ctx, span)

	ctx1, cancelFunc := context.WithCancel(ctx)
	cc.mu.Lock()
	cc.mu.cancelFunc = cancelFunc
	cc.mu.Unlock()

	t := time.Now()
	cmd := data[0]
	data = data[1:]
	cc.lastCmd = string(hack.String(data))
	token := cc.server.getToken()
	defer func() {
		cc.ctx.SetProcessInfo("", t, mysql.ComSleep)
		cc.server.releaseToken(token)
		span.Finish()
	}()

	if cmd < mysql.ComEnd {
		cc.ctx.SetCommandValue(cmd)
	}

	dataStr := string(hack.String(data))
	switch cmd {
	case mysql.ComPing, mysql.ComStmtClose, mysql.ComStmtSendLongData, mysql.ComStmtReset,
		mysql.ComSetOption, mysql.ComChangeUser:
		cc.ctx.SetProcessInfo("", t, cmd)
	case mysql.ComInitDB:
		cc.ctx.SetProcessInfo("use "+dataStr, t, cmd)
	}

	switch cmd {
	case mysql.ComSleep:
		// TODO: According to mysql document, this command is supposed to be used only internally.
		// So it's just a temp fix, not sure if it's done right.
		// Investigate this command and write test case later.
		return nil
	case mysql.ComQuit:
		return io.EOF
	case mysql.ComQuery: // Most frequently used command.
		// For issue 1989
		// Input payload may end with byte '\0', we didn't find related mysql document about it, but mysql
		// implementation accept that case. So trim the last '\0' here as if the payload an EOF string.
		// See http://dev.mysql.com/doc/internals/en/com-query.html
		if len(data) > 0 && data[len(data)-1] == 0 {
			data = data[:len(data)-1]
			dataStr = string(hack.String(data))
		}
		return cc.handleQuery(ctx1, dataStr)
	case mysql.ComPing:
		return cc.writeOK()
	case mysql.ComInitDB:
		if err := cc.useDB(ctx1, dataStr); err != nil {
			return err
		}
		return cc.writeOK()
	case mysql.ComFieldList:
		return cc.handleFieldList(dataStr)
	case mysql.ComStmtPrepare:
		return cc.handleStmtPrepare(dataStr)
	case mysql.ComStmtExecute:
		return cc.handleStmtExecute(ctx1, data)
	case mysql.ComStmtFetch:
		return cc.handleStmtFetch(ctx1, data)
	case mysql.ComStmtClose:
		return cc.handleStmtClose(data)
	case mysql.ComStmtSendLongData:
		return cc.handleStmtSendLongData(data)
	case mysql.ComStmtReset:
		return cc.handleStmtReset(data)
	case mysql.ComSetOption:
		return cc.handleSetOption(data)
	case mysql.ComChangeUser:
		return cc.handleChangeUser(ctx1, data)
	default:
		return mysql.NewErrf(mysql.ErrUnknown, "command %d not supported now", cmd)
	}
}
443266
func (ed *Dispatcher) HandleDisconnectEvent(e esdispatcher.Event) {
	evt := e.(*DisconnectEvent)

	if ed.connection == nil {
		evt.Errch <- errors.New("connection already closed")
		return
	}

	logger.Debug("Closing connection due to disconnect event...")

	ed.connection.Close()
	ed.connection = nil
	ed.setConnectedPeer(nil)

	evt.Errch <- nil
}