func (r *fake_conn) run_queue(conn *net.UnixConn) {
	defer conn.Close()

	for {
		select {
		case <-r.end:
			return

		default:
			buffer := make([]byte, 1<<16)

			conn.SetReadDeadline(time.Now().Add(1000 * time.Millisecond))
			s, _, err := conn.ReadFrom(buffer)
			switch t_err := err.(type) {
			case nil:
			case net.Error:
				if !t_err.Timeout() {
					panic(err)
				}
			default:
				panic(err)
			}

			if s > 0 {
				r.queue <- buffer[0:s]
			}

		}
	}

}
示例#2
0
func daemonIpcHandleConn(conn *net.UnixConn) {
	defer cluegetterRecover("daemonIpcHandleConn")
	defer conn.Close()

	for {
		message, err := bufio.NewReader(conn).ReadString('\x00')
		if err != nil {
			if message != "" {
				Log.Info("Got %s on IPC Socket. Ignoring.", err.Error())
			}
			return
		}

		kv := strings.SplitN(message, " ", 2)
		handle := strings.TrimRightFunc(kv[0], func(v rune) bool { return v == '\x00' })
		callback := ipcHandlers[handle]
		v := ""
		if len(kv) > 1 {
			v = strings.TrimRightFunc(kv[1], func(v rune) bool { return v == '\x00' })
		}
		if callback == nil {
			Log.Debug("Received IPC message but no such pattern was registered, ignoring: <%s>%s", handle, v)
			return
		}

		callback(v)
	}
}
示例#3
0
文件: server.go 项目: akramer/lateral
func (i *instance) connectionHandler(c *net.UnixConn) {
	defer c.Close()
	for {
		req, err := readRequest(c)
		if err == io.EOF {
			return // Client closed the connection.
		}
		if err != nil {
			glog.Errorln("Failed to read a message from socket:", err)
		}
		f, t := funcMap[req.Type]
		if t != true {
			sendError(c, fmt.Errorf("unknown request type"))
			continue
		}
		resp, err := f(i, req)
		if err != nil {
			sendError(c, err)
			continue
		}
		err = writeResponse(c, resp)
		if err != nil {
			glog.Errorln("Failed to write a message to socket:", err)
			return
		}
	}
}
示例#4
0
文件: sio.go 项目: jmore-reachtech/io
// handle the socket connection. When data comes in on the socket write it
// to the channel so the serial port can see it. When data comes in over the
// channel translate the message and write it to the socket
func handleSocket(conn *net.UnixConn, ch chan []byte) {
	defer conn.Close()

	readCh := make(chan []byte)

	go socketRead(conn, readCh)

	for {
		select {
		case s := <-ch:
			{
				// map micro -> gui
				trans := mapMicro.ItemTranslate(string(s))
				_, err := conn.Write([]byte(trans))
				if err != nil {
					fmt.Println(err)
				}
			}
		case r := <-readCh:
			{
				ch <- r
			}
		case <-time.After(timeout):
			continue
		}
	}
}
示例#5
0
func (srv *Server) handleConn(conn *net.UnixConn) {
	err := srv.doRequest(conn)
	resp := "Ok\n"
	if err != nil {
		resp = err.Error()
	}

	conn.Write(([]byte)(resp))
	conn.Close()
}
示例#6
0
文件: server.go 项目: yunabe/codelab
func HandleConnection(conn *net.UnixConn) {
	defer conn.Close()
	defer fmt.Println("closing...")
	r := bufio.NewReader(conn)
	w := bufio.NewWriter(conn)

	req, err := ReceiveRequest(r)
	if req != nil {
		fmt.Println("req.Name =", *req.Name)
		res := new(Response)
		res.Name = proto.String("hello hello!")
		SendResponse(w, res)
		w.Flush()
	} else {
		fmt.Println("Failed to receive a request:", err)
	}
}
示例#7
0
func (ch *ctlSockHandler) handleConnection(conn *net.UnixConn) {
	buf := make([]byte, ReadBufSize)
	for {
		n, err := conn.Read(buf)
		if err == io.EOF {
			conn.Close()
			return
		} else if err != nil {
			tlog.Warn.Printf("ctlsock: Read error: %#v", err)
			conn.Close()
			return
		}
		if n == ReadBufSize {
			tlog.Warn.Printf("ctlsock: request too big (max = %d bytes)", ReadBufSize-1)
			conn.Close()
			return
		}
		buf = buf[:n]
		var in RequestStruct
		err = json.Unmarshal(buf, &in)
		if err != nil {
			tlog.Warn.Printf("ctlsock: Unmarshal error: %#v", err)
			errorMsg := ResponseStruct{
				ErrNo:   int32(syscall.EINVAL),
				ErrText: err.Error(),
			}
			sendResponse(&errorMsg, conn)
		}
		ch.handleRequest(&in, conn)
		// Restore original size.
		buf = buf[:cap(buf)]
	}
}
示例#8
0
func (s *Server) serveConn(in, out *net.UnixConn) {
	defer in.Close()
	defer out.Close()

	go func() {
		for {
			vals := []int{}
			incomingMu.Lock()
			for k := range incoming {
				vals = append(vals, k)
			}
			incomingMu.Unlock()
			sort.Ints(vals)
			log.Infof("the server: values still being waited on: %#v", vals)
			time.Sleep(5 * time.Second)
		}
	}()

	inBuff := bufio.NewReader(in)
	for {
		msg := &ClientMsg{}

		select {
		case err := <-s.decoder(msg, inBuff):
			if err != nil {
				log.Errorf("problem with client message: %s", err)
				continue
			}
		case <-time.After(30 * time.Second):
			return
		}

		incomingMu.Lock()
		incoming[int(msg.ID)] = true
		incomingMu.Unlock()

		if msg.Type == ClientKeepAlive {
			log.Infof("%#v", msg)
			continue
		}

		log.Infof("server received msg.ID = %d", msg.ID)
		reg, ok := s.registry[msg.Handler]
		if !ok {
			log.Infof("can not locate Handler %q", msg.Handler)
			continue
		}

		go func(msg *ClientMsg, reg *register) {
			srvMsg, err := reg.handler(msg)
			if err != nil {
				srvMsg.ID = msg.ID
				srvMsg.Data = []byte(fmt.Sprintf("handler(%s) error: %s", msg.Handler, err))
				reg.Lock()
				defer reg.Unlock()
				log.Infof("server: writing error response to client for ID: %d", msg.ID)
				if err := srvMsg.Encode(out); err != nil {
					log.Infof("cannot write to the client: %s", err)
				}
				return
			}
			reg.Lock()
			defer reg.Unlock()
			log.Infof("server: writing response to client for ID: %d", msg.ID)
			for {
				if err := srvMsg.Encode(out); err != nil {
					log.Infof("cannot write to the client: %s", err)
					s.bufferSize += serverMsgHeader + len(srvMsg.Data)
					if err := out.SetWriteBuffer(s.bufferSize); err != nil {
						log.Infof("cannot extend the write buffer, call will fail: %s", err)
						srvMsg = &ServerMsg{ID: msg.ID, Data: []byte("buffer cannot be made large enough to hold output message")}
						if err := srvMsg.Encode(out); err != nil {
							// TODO(johnsiilver): make this an exponential backoff with a time limit on iterations.
							log.Infof("can't send error message")
							continue
						}
						break
					}
					continue
				}
				break
			}
			incomingMu.Lock()
			delete(incoming, int(msg.ID))
			incomingMu.Unlock()
		}(msg, reg)
	}
}