//  The server thread reads the file from disk in chunks, and sends
//  each chunk to the client as a separate message. We only have one
//  test file, so open that once and then serve it out as needed:
195923
func server_thread() {
	file, err := os.Open("testdata")
	if err != nil {
		panic(err)
	}

	router, _ := zmq.NewSocket(zmq.ROUTER)
	//  Default HWM is 1000, which will drop messages here
	//  since we send more than 1,000 chunks of test data,
	//  so set an infinite HWM as a simple, stupid solution:
	router.SetRcvhwm(0)
	router.SetSndhwm(0)
	router.Bind("tcp://*:6000")
	for {
		//  First frame in each message is the sender identity
		identity, err := router.Recv(0)
		if err != nil {
			break //  Shutting down, quit
		}

		//  Second frame is "fetch" command
		command, _ := router.Recv(0)
		if command != "fetch" {
			panic("command != \"fetch\"")
		}

		chunk := make([]byte, CHUNK_SIZE)
		for {
			n, _ := io.ReadFull(file, chunk)
			router.SendMessage(identity, chunk[:n])
			if n == 0 {
				break //  Always end with a zero-size frame
			}
		}
	}
	file.Close()
}
800997
func main() {
	rand.Seed(time.Now().UnixNano())

	go client_task()
	go client_task()
	go client_task()
	go server_task()

	//  Run for 5 seconds then quit
	time.Sleep(5 * time.Second)
}
334174
func (f ReadHandlerFunc) ServeRead(resp ResponseWriter, req *ReadRequest) {
	f(resp, req)
}
1199630
func (u *multiuploader) send(c chunk) error {
	params := &s3.UploadPartInput{
		Bucket:               u.in.Bucket,
		Key:                  u.in.Key,
		Body:                 c.buf,
		UploadId:             &u.uploadID,
		SSECustomerAlgorithm: u.in.SSECustomerAlgorithm,
		SSECustomerKey:       u.in.SSECustomerKey,
		PartNumber:           &c.num,
	}
	resp, err := u.cfg.S3.UploadPartWithContext(u.ctx, params, u.cfg.RequestOptions...)
	// put the byte array back into the pool to conserve memory
	u.bufferPool.Put(c.part)
	if err != nil {
		return err
	}

	n := c.num
	completed := &s3.CompletedPart{ETag: resp.ETag, PartNumber: &n}

	u.m.Lock()
	u.parts = append(u.parts, completed)
	u.m.Unlock()

	return nil
}
525485
func (u *multiuploader) readChunk(ch chan chunk) {
	defer u.wg.Done()
	for {
		data, ok := <-ch

		if !ok {
			break
		}

		if u.geterr() == nil {
			if err := u.send(data); err != nil {
				u.seterr(err)
			}
		}
	}
}
23459
func main() {
	app := iris.New()
	s := sse.New()
	/*
		This creates a new stream inside of the scheduler.
		Seeing as there are no consumers, publishing a message
		to this channel will do nothing.
		Clients can connect to this stream once the iris handler is started
		by specifying stream as a url parameter, like so:
		http://localhost:8080/events?stream=messages
	*/
	s.CreateStream("messages")

	app.Any("/events", iris.FromStd(s.HTTPHandler))

	go func() {
		// You design when to send messages to the client,
		// here we just wait 5 seconds to send the first message
		// in order to give u time to open a browser window...
		time.Sleep(5 * time.Second)
		// Publish a payload to the stream.
		s.Publish("messages", &sse.Event{
			Data: []byte("ping"),
		})

		time.Sleep(3 * time.Second)
		s.Publish("messages", &sse.Event{
			Data: []byte("second message"),
		})
		time.Sleep(2 * time.Second)
		s.Publish("messages", &sse.Event{
			Data: []byte("third message"),
		})

	}() // ...

	app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
}
1161476
func sendUntilErr(sendInterval int) {
	i := 1
	for {
		time.Sleep(time.Duration(sendInterval) * time.Second)
		err := SendMessage("2", "all", "objectupdate", "2.UsrSchedule_v1_1")
		if err != nil {
			fmt.Println("failed to send join message", err.Error())
			return
		}
		fmt.Println("objectupdate", i)
		i++
	}
}
89484
func (c *Client) Send(b []byte) ([]byte, error) {
	c.Lock()
	defer c.Unlock()

	if err := c.w.Write(b); err != nil {
		return nil, err
	}
	return c.r.Read()
}
1262723
func (s *SCP) Receive(srcFile string, dest io.Writer) (os.FileInfo, error) {
	var info os.FileInfo
	srcFile = realPath(filepath.Clean(srcFile))
	err := runSinkSession(s.client, srcFile, false, "", false, true, func(s *sinkSession) error {
		var timeHeader timeMsgHeader
		h, err := s.ReadHeaderOrReply()
		if err != nil {
			return fmt.Errorf("failed to read scp message header: err=%s", err)
		}
		var ok bool
		timeHeader, ok = h.(timeMsgHeader)
		if !ok {
			return fmt.Errorf("expected time message header, got %+v", h)
		}

		h, err = s.ReadHeaderOrReply()
		if err != nil {
			return fmt.Errorf("failed to read scp message header: err=%s", err)
		}
		fileHeader, ok := h.(fileMsgHeader)
		if !ok {
			return fmt.Errorf("expected file message header, got %+v", h)
		}
		err = s.CopyFileBodyTo(fileHeader, dest)
		if err != nil {
			return fmt.Errorf("failed to copy file: err=%s", err)
		}

		info = NewFileInfo(srcFile, fileHeader.Size, fileHeader.Mode, timeHeader.Mtime, timeHeader.Atime)
		return nil
	})
	return info, err
}
1354834
func main() {
	done := make(chan error)
	createServer(done)
	// add our clients connection
	for i := 0; i < 100; i++ {
		i := i
		go createClient("ws://localhost:8070/ws", "http://localhost/", i)
	}
	// handle server's termination
	log.Fatal(<-done)
}
466937
func (c *Channel) OnRead(f OnReadFunc) {
	// Create a new read handler for this channel.
	// Previous handlers are stopped first.
	handlerStopped := c.readHandler.New()

	// Start the handler goroutine.
	go func() {
		for {
			select {
			case data := <-c.readChan:
				// Call the callback in a new goroutine.
				go func() {
					// Recover panics and log the error.
					defer func() {
						if e := recover(); e != nil {
							log.L.Errorf("glue: panic while calling onRead function: %v\n%s", e, debug.Stack())
						}
					}()

					// Trigger the on read event function.
					f(data)
				}()
			case <-c.s.isClosedChan:
				// Release this goroutine if the socket is closed.
				return
			case <-handlerStopped:
				// Release this goroutine.
				return
			}
		}
	}()
}
1249796
func (s *Server) Handle(c *Connection) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	s.messages = append(s.messages, "")

	s.readHello(c)
	s.readSender(c)
	s.readRecipients(c)
	s.readData(c)

	c.conn.Close()
}
389614
func (m *MockClient) MultiRead(arg0 context.Context, arg1 []string, arg2 ...dosa.DomainObject) (dosa.MultiResult, error) {
	varargs := []interface{}{arg0, arg1}
	for _, a := range arg2 {
		varargs = append(varargs, a)
	}
	ret := m.ctrl.Call(m, "MultiRead", varargs...)
	ret0, _ := ret[0].(dosa.MultiResult)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
1183519
func main() {
	var l server.ListenConst

	if useDomainSocket {
		l = server.UnixListener(sockPath)
	} else {
		l = server.TCPListener(port)
	}

	protocols := []protocol.Components{binprot.Components, textprot.Components}

	var o orcas.OrcaConst
	var h2 handlers.HandlerConst
	var h1 handlers.HandlerConst

	// Choose the proper L1 handler
	if l1inmem {
		h1 = inmem.New
	} else if chunked {
		h1 = memcached.Chunked(l1sock)
	} else if l1batched {
		h1 = memcached.Batched(l1sock, batchOpts)
	} else {
		h1 = memcached.Regular(l1sock)
	}

	if l2enabled {
		o = orcas.L1L2
		h2 = memcached.Regular(l2sock)
	} else {
		o = orcas.L1Only
		h2 = handlers.NilHandler
	}

	// Add the locking wrapper if requested. The locking wrapper can either allow mutltiple readers
	// or not, with the same difference in semantics between a sync.Mutex and a sync.RWMutex. If
	// chunking is enabled, we want to ensure that stricter locking is enabled, since concurrent
	// sets into L1 with chunking can collide and cause data corruption.
	var lockset uint32
	if locked {
		if chunked || !multiReader {
			o, lockset = orcas.Locked(o, false, uint8(concurrency))
		} else {
			o, lockset = orcas.Locked(o, true, uint8(concurrency))
		}
	}

	go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)

	if l2enabled {
		// If L2 is enabled, start the batch L1 / L2 orchestrator
		l = server.TCPListener(batchPort)
		o := orcas.L1L2Batch

		if locked {
			o = orcas.LockedWithExisting(o, lockset)
		}

		go server.ListenAndServe(l, protocols, server.Default, o, h1, h2)
	}

	// Block forever
	wg := sync.WaitGroup{}
	wg.Add(1)
	wg.Wait()
}
271220
func (this *Response) Sendfile(filename string, opt ...interface{}) {
	http.ServeFile(this.Writer, this.req.Request.Request, filename)
}
1332236
func (self *SocketHandler) Marshal(record *LogRecord) ([]byte, error) {
	r := SocketLogRecord{
		CreatedTime: record.CreatedTime,
		AscTime:     record.AscTime,
		Name:        record.Name,
		Level:       record.Level,
		PathName:    record.PathName,
		FileName:    record.FileName,
		LineNo:      record.LineNo,
		FuncName:    record.FuncName,
		Format:      record.Format,
		UseFormat:   record.UseFormat,
		Message:     record.Message,
	}
	var buf bytes.Buffer
	encoder := gob.NewEncoder(&buf)
	err := encoder.Encode(r)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
1352957
func (m *ObserverMultiplexer) ServerRequest(hdr *Header, body interface{}) {
	mapConcurrent(func(n Observer) { n.ServerRequest(hdr, body) }, m.rpcObservers)
}