当前位置: 首页>>代码示例>>Golang>>正文


Golang ReadWriteCloser.Close方法代码示例

本文整理汇总了Golang中io.ReadWriteCloser.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang ReadWriteCloser.Close方法的具体用法?Golang ReadWriteCloser.Close怎么用?Golang ReadWriteCloser.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在io.ReadWriteCloser的用法示例。


在下文中一共展示了ReadWriteCloser.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: HandleClient

func (srv *Server) HandleClient(raw io.ReadWriteCloser) {
	defer raw.Close()
	/*raw, err := kiss.LLObfsServerHandshake(srv.prv.PublicKey(), raw)
	if err != nil {
		kilog.Debug("directory: client failed LLObfs handshake: %v", err.Error())
		return
	}*/
	var theirKey natrium.EdDSAPublic
	// "verifier" that copies down their public key
	copier := func(haha natrium.EdDSAPublic) bool {
		theirKey = haha
		return true
	}
	sock, err := kiss.KiSSNamedHandshake(srv.prv, copier, raw)
	if err != nil {
		kilog.Debug("directory: client failed KiSS handshake: %v", err.Error())
		return
	}
	defer sock.Close()

	var request clntRequest
	err = struc.Unpack(sock, &request)
	if err != nil {
		kilog.Debug("directory: client sent malformed request: %v", err.Error())
		return
	}
	//fmt.Println(request)
	srv.rqDispatch(sock, request)
}
开发者ID:ProjectNiwl,项目名称:sagiri,代码行数:29,代码来源:server.go

示例2: ServeConn

// ServeConn runs a single connection.
//
// ServeConn blocks, serving the connection until the client hangs up.
func (s *Server) ServeConn(conn io.ReadWriteCloser) {
	// First create the yamux server to wrap this connection
	mux, err := yamux.Server(conn, nil)
	if err != nil {
		conn.Close()
		log.Printf("[ERR] plugin: %s", err)
		return
	}

	// Accept the control connection
	control, err := mux.Accept()
	if err != nil {
		mux.Close()
		log.Printf("[ERR] plugin: %s", err)
		return
	}

	// Create the broker and start it up
	broker := newMuxBroker(mux)
	go broker.Run()

	// Use the control connection to build the dispenser and serve the
	// connection.
	server := rpc.NewServer()
	server.RegisterName("Dispenser", &dispenseServer{
		ProviderFunc:    s.ProviderFunc,
		ProvisionerFunc: s.ProvisionerFunc,

		broker: broker,
	})
	server.ServeConn(control)
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:35,代码来源:server.go

示例3: doLoris

func doLoris(conn io.ReadWriteCloser, victimUri *url.URL, activeConnectionsCh chan<- int, requestHeader []byte) {
	defer conn.Close()

	if _, err := conn.Write(requestHeader); err != nil {
		log.Printf("Cannot write requestHeader=[%v]: [%s]\n", requestHeader, err)
		return
	}

	activeConnectionsCh <- 1
	defer func() { activeConnectionsCh <- -1 }()

	readerStopCh := make(chan int, 1)
	go nullReader(conn, readerStopCh)

	for i := 0; i < *contentLength; i++ {
		select {
		case <-readerStopCh:
			return
		case <-time.After(*sleepInterval):
		}
		if _, err := conn.Write(sharedWriteBuf); err != nil {
			log.Printf("Error when writing %d byte out of %d bytes: [%s]\n", i, *contentLength, err)
			return
		}
	}
}
开发者ID:gasperko,项目名称:goloris,代码行数:26,代码来源:goloris.go

示例4: getflag

func getflag(c io.ReadWriteCloser) {
	defer c.Close()
	var flag_id string
	fmt.Fprintln(c, "flag_id: ")
	_, err := fmt.Fscanln(c, &flag_id)
	if err != nil {
		return
	}
	var cookie string
	fmt.Fprintln(c, "token_id: ")
	_, err = fmt.Fscanln(c, &cookie)
	if err != nil {
		return
	}
	entry := db.Get(flag_id)
	if entry == nil {
		fmt.Fprintln(c, "flagval: no_entry_exists")
		log.Println("getflag: request for non-existant entry")
	} else if cookie == entry[0] {
		fmt.Fprintln(c, "flagval:", entry[1])
		log.Println("getflag: got")
	} else {
		fmt.Fprintln(c, "flagval: getflag_auth_fail")
		log.Println("getflag: auth fail")
	}
	return
}
开发者ID:AdaLovelance,项目名称:ictf-framework,代码行数:27,代码来源:tattletale.go

示例5: NewClient

// NewClient creates a client from an already-open connection-like value.
// Dial is typically used instead.
func NewClient(conn io.ReadWriteCloser) (*Client, error) {
	// Create the yamux client so we can multiplex
	mux, err := yamux.Client(conn, nil)
	if err != nil {
		conn.Close()
		return nil, err
	}

	// Connect to the control stream.
	control, err := mux.Open()
	if err != nil {
		mux.Close()
		return nil, err
	}

	// Create the broker and start it up
	broker := newMuxBroker(mux)
	go broker.Run()

	// Build the client using our broker and control channel.
	return &Client{
		broker:  broker,
		control: rpc.NewClient(control),
	}, nil
}
开发者ID:AssertSelenium,项目名称:terraform,代码行数:27,代码来源:client.go

示例6: attach

func (h *attachHandler) attach(req *host.AttachReq, conn io.ReadWriteCloser) {
	defer conn.Close()

	g := grohl.NewContext(grohl.Data{"fn": "attach", "job.id": req.JobID})
	g.Log(grohl.Data{"at": "start"})
	attachWait := make(chan struct{})
	job := h.state.AddAttacher(req.JobID, attachWait)
	if job == nil {
		defer h.state.RemoveAttacher(req.JobID, attachWait)
		if _, err := conn.Write([]byte{host.AttachWaiting}); err != nil {
			return
		}
		// TODO: add timeout
		<-attachWait
		job = h.state.GetJob(req.JobID)
	}

	success := make(chan struct{})
	failed := make(chan struct{})
	opts := &AttachRequest{
		Job:        job,
		Logs:       req.Flags&host.AttachFlagLogs != 0,
		Stream:     req.Flags&host.AttachFlagStream != 0,
		Height:     req.Height,
		Width:      req.Width,
		Attached:   success,
		ReadWriter: conn,
		Streams:    make([]string, 0, 3),
	}
	if req.Flags&host.AttachFlagStdin != 0 {
		opts.Streams = append(opts.Streams, "stdin")
	}
	if req.Flags&host.AttachFlagStdout != 0 {
		opts.Streams = append(opts.Streams, "stdout")
	}
	if req.Flags&host.AttachFlagStderr != 0 {
		opts.Streams = append(opts.Streams, "stderr")
	}

	go func() {
		select {
		case <-success:
			conn.Write([]byte{host.AttachSuccess})
			close(success)
		case <-failed:
		}
		close(attachWait)
	}()
	if err := h.backend.Attach(opts); err != nil {
		select {
		case <-success:
		default:
			close(failed)
			conn.Write(append([]byte{host.AttachError}, err.Error()...))
		}
		g.Log(grohl.Data{"status": "error", "err": err})
		return
	}
	g.Log(grohl.Data{"at": "finish"})
}
开发者ID:korya,项目名称:flynn-host,代码行数:60,代码来源:attach.go

示例7: init

// init initializes the conn to the ircServer and start all the gouroutines
// requires to run ircBot
func (bot *ircBot) init(conn io.ReadWriteCloser) {
	glog.Infoln("Init bot", bot)

	quit := make(chan struct{})
	receive := make(chan string)

	go bot.readSocket(quit, receive, conn)

	// Listen for incoming messages in background thread
	go bot.listenSendMonitor(quit, receive, conn)

	go func(bot *ircBot, conn io.Closer) {
		for {
			select {
			case <-bot.closing:
				err := conn.Close()
				if err != nil {
					glog.Errorln("An error occured while closing the conn of", bot, err)
				}
				close(quit)
				return
			}
		}
	}(bot, conn)

	bot.RLock()
	if bot.serverPass != "" {
		bot.SendRaw("PASS " + bot.serverPass)
	}
	bot.RUnlock()

	bot.SendRaw("PING Bonjour")
}
开发者ID:fazzzmZozo,项目名称:botbot-bot,代码行数:35,代码来源:irc.go

示例8: handleConnection

func (g *GraphiteTcpServer) handleConnection(conn io.ReadWriteCloser) {
	scanner := bufio.NewScanner(conn)
	defer conn.Close()

	// Create a channel for the metrics
	addChan := make(chan metrics.Metric, 1000)
	g.backend.AddMetricChan(addChan)
	defer close(addChan)

	for scanner.Scan() {
		// PARSE METRIC LINES
		//err, m :=
		err, m := parseGraphiteLine(scanner.Text())
		if err == nil {
			// Send parsed metric to the back-end
			addChan <- m
		} else {
			conn.Write([]byte(err.Error()))
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Printf("Error while parsing text: %v", err)
	}
}
开发者ID:rayleyva,项目名称:MetricBase,代码行数:25,代码来源:graphiteTcp.go

示例9: serve

func serve(c io.ReadWriteCloser, call []string) {
	defer c.Close()
	e := serveExec(c, call)
	if e != nil {
		common.FDumpError(c, e)
	}
}
开发者ID:kissthink,项目名称:gobox,代码行数:7,代码来源:telnetd.go

示例10: Run

// Run starts reading bytes from the serial port, (re)opening it if needed
// and sends the read bytes to the channel.
// Run blocks so should be called as a go routine.
func (sc *serialToChan) Run() {
	// Ser is nil when closed.
	var ser io.ReadWriteCloser

	for {
		// Open the serial port.
		if ser == nil {
			// Open serial port.
			log.Printf("LoopSerial: Opening the port.\n")
			var err error
			// Open the serial port.
			ser, err = openSerial(sc.port)
			if err != nil {
				log.Printf("LoopSerial: Error opening the port: %s.\n", err.Error())
				ser = nil
				time.Sleep(5 * time.Second)
			}
		}

		// b is nil if no bytes were received.
		var b []byte

		if ser != nil {
			// Read buf from serial.
			b = getBuffer("LoopSerial: asking for buffer.")
			n, err := ser.Read(b)
			if err != nil || n == 0 {
				// Error reading the serial port.
				log.Printf("LoopSerial: Error reading the serial port. Closing it.")
				// Return and invalidate the buffer.
				putBuffer(b, "LoopSerial: returning buffer because of read error.")
				b = nil
				// Close serial.
				ser.Close()
				ser = nil
			} else {
				b = b[:n]
			}
		}

		if b != nil {
			// Send the bytes to the channel.
			sc.bytesChan <- b
			// Set b to nil to indicate that it has been sent.
			b = nil
		}

		// Check if the done channel has been closed, but don't wait.
		select {
		case <-sc.done:
			// Time to stop.
			if ser != nil {
				ser.Close()
			}
			close(sc.bytesChan)
			return
		default:
		}
	}
}
开发者ID:peterzandbergen,项目名称:gps2tcp,代码行数:63,代码来源:gpsserial.go

示例11: handleMessage

func (m *CircularMPI) handleMessage(conn io.ReadWriteCloser) {
	defer conn.Close()
	buf, err := ioutil.ReadAll(conn)
	if err != nil {
		m.logger.Println(err)
		conn.Write([]byte{'N', 'O'})
		return
	}
	conn.Write([]byte{'O', 'K'})

	go func() {
		states := make(map[string]Versioner)
		data := bytes.NewBuffer(buf)
		st, err := decodeData(data)
		if err != nil {
			m.logger.Println(err)
		}
		states = st
		m.logger.Println(m.me, " Received ")
		m.cleanLocalStreams(states)
		m.prepareData(states)
		if len(states) == 0 {
			m.logger.Println("Nothing to send Going")
			return
		}
		// Ne need to clean local streams
		for key, v := range states {
			m.Dummy.Write(key, v)
		}
		m.sendData(states)
	}()
}
开发者ID:postfix,项目名称:dolphin,代码行数:32,代码来源:tcp_circular.go

示例12: handleAgent

func handleAgent(ll *log.Log, cc io.ReadWriteCloser) {
	defer cc.Close()
	client := osprocess.New(nil)
	agent := rpc.RepresentAgent(cc, client)

	for i := 0; ; i++ {
		ll.Info("starting program")

		res, err := agent.StartProcess(&rpc.StartProcessReq{
			ProgramName: fmt.Sprintf("echoer v%d i was told to do this by the supervisor", i),
		})
		if err != nil {
			ll.Err(err).Error("couldn't send command to remote agent")
			return
		}
		ll.KV("process.id", res.ProcessID).Info("agent is running program")

		time.Sleep(3 * time.Second)

		ll.Info("stopping program")
		_, err = agent.StopProcess(&rpc.StopProcessReq{ProcessID: res.ProcessID, Timeout: time.Second})
		if err != nil {
			ll.Err(err).Error("couldn't send command to remote agent")
			return
		}
	}

}
开发者ID:aybabtme,项目名称:deployotron,代码行数:28,代码来源:main.go

示例13: Accept

// Accept starts a new SMTP session using io.ReadWriteCloser
func Accept(remoteAddress string, conn io.ReadWriteCloser, storage storage.Storage, messageChan chan *data.Message, hostname string, monkey monkey.ChaosMonkey) {
	defer conn.Close()

	proto := smtp.NewProtocol()
	proto.Hostname = hostname
	var link *linkio.Link
	reader := io.Reader(conn)
	writer := io.Writer(conn)
	if monkey != nil {
		linkSpeed := monkey.LinkSpeed()
		if linkSpeed != nil {
			link = linkio.NewLink(*linkSpeed * linkio.BytePerSecond)
			reader = link.NewLinkReader(io.Reader(conn))
			writer = link.NewLinkWriter(io.Writer(conn))
		}
	}

	session := &Session{conn, proto, storage, messageChan, remoteAddress, false, "", link, reader, writer, monkey}
	proto.LogHandler = session.logf
	proto.MessageReceivedHandler = session.acceptMessage
	proto.ValidateSenderHandler = session.validateSender
	proto.ValidateRecipientHandler = session.validateRecipient
	proto.ValidateAuthenticationHandler = session.validateAuthentication
	proto.GetAuthenticationMechanismsHandler = func() []string { return []string{"PLAIN"} }

	session.logf("Starting session")
	session.Write(proto.Start())
	for session.Read() == true {
		if monkey != nil && monkey.Disconnect != nil && monkey.Disconnect() {
			session.conn.Close()
			break
		}
	}
	session.logf("Session ended")
}
开发者ID:jackc,项目名称:MailHog-Server,代码行数:36,代码来源:session.go

示例14: reader

func (gc *Goctl) reader(c io.ReadWriteCloser) error {
	defer gc.logger.Info("Connection closed.")
	defer c.Close()

	gc.logger.Info("New connection.")
	for {
		buf, err := Read(c)
		if err != nil {
			gc.logger.Error("Error reading from connection.", "error", err)
			return err
		}

		cmd := strings.Split(string(buf), "\u0000")
		gc.logger.Debug("Got command.", "cmd", cmd)
		var resp string
		if h := gc.handlers[cmd[0]]; h != nil {
			resp = h.Run(gc, cmd[1:])
		} else {
			resp = fmt.Sprintf("ERROR: unknown command: '%s'.", cmd[0])
		}
		gc.logger.Debug("Responding.", "resp", resp)
		Write(c, []byte(resp))
	}
	/* NOTREACHED */
}
开发者ID:bjc,项目名称:goctl,代码行数:25,代码来源:goctl.go

示例15: Login

// logs a player in from an incoming connection, creating a player
// in the world if they successfully connect
func Login(rwc io.ReadWriteCloser, ip net.Addr) {
	showTitle(rwc)
	for i := 0; i < retries; i++ {
		user, err := authenticate(rwc, ip)
		switch err {
		case nil:
			world.SpawnPlayer(rwc, user)
			return

		case ErrAuth:
			log.Printf("Failed login from %s", ip)
			_, err = rwc.Write([]byte("Incorrect username or password, please try again\n"))
			if err != nil {
				break
			}
		case ErrDupe:
			ok, err := handleDupe(user, rwc)
			if ok && err == nil {
				kick(user)
				world.SpawnPlayer(rwc, user)
				return
			}
		case ErrNotSetup:
			rwc.Close()
			return
		}
		if err != nil {
			log.Printf("Error during login of user from %s: %s", ip, err)
			return
		}
	}
}
开发者ID:natefinch,项目名称:claymud,代码行数:34,代码来源:auth.go


注:本文中的io.ReadWriteCloser.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。