예제 #1
1
// handler handles a single TCP Connection
func (t *TcpListener) handler(conn *net.TCPConn, id string) {
	// connection cleanup function
	defer func() {
		t.wg.Done()
		conn.Close()
		log.Printf("Closed TCP Connection from %s", conn.RemoteAddr())
		// Add one connection potential back to channel when this one closes
		t.accept <- true
		t.forget(id)
	}()

	scanner := bufio.NewScanner(conn)
	for {
		select {
		case <-t.done:
			return
		default:
			if !scanner.Scan() {
				return
			}
			buf := scanner.Bytes()
			select {
			case t.in <- buf:
			default:
				log.Printf(dropwarn, string(buf))
			}
		}
	}
}
예제 #2
0
파일: tcp01.go 프로젝트: ra/go-samp
//
// A TCP 'echo' example.
// Demonstrates using a timeout, and a 'graceful' shutdown if one occurs.
// 'Tested' using 'telnet localhost 45678'
//
func runReads(tcpConn *net.TCPConn) bool {
	br := bufio.NewReader(tcpConn)
	for {
		// Set a timeout value, which needs to be set before each and every read.
		d := time.Duration(30 * 1e9) // 30 seconds
		w := time.Now()              // from now
		w = w.Add(d)
		tcpConn.SetReadDeadline(w) // Set the deadline
		//
		buffer, err := br.ReadBytes('\n') // '\n' is delimiter
		// If the read times out, this prints something like:
		// Error = read tcp 127.0.0.1:57609: resource temporarily unavailable
		if err != nil {
			fmt.Printf("Error = %v\n", err)
			return false
			// panic("wtf04")
		}
		//
		fmt.Printf("Bytes Read: %d\n", len(buffer))
		var data = string(buffer)
		fmt.Printf("Data Read: |%q|\n", data)

		// This is now an 'echo' example.
		out := "echo: " + data
		tcpConn.Write([]byte(out))

		// The \r in this data from telnet is a bit surprising ...
		if data == "quit\r\n" {
			fmt.Println("Breaking....")
			break
		}
	}
	return true
}
예제 #3
0
파일: test.go 프로젝트: jmptrader/Tecellate
func listenForMoveRequests(conn *net.TCPConn) {
	listenServe := make(chan []uint8)
	easynet.TieConnToChannel(conn, listenServe)
	for data := range listenServe {
		r := new(ttypes.BotMoveRequest)
		err := json.Unmarshal(data, r)
		easynet.DieIfError(err, "JSON error")

		if r.Kill {
			fmt.Printf("Bot on %s received kill signal\n", os.Args[0])
			os.Exit(0)
		}

		fmt.Printf("Bot at %d, %d received messages: %v\n", r.YourX, r.YourY, r.Messages)
		fmt.Printf("  Sees other bots: %v\n", r.OtherBots)
		//Do something

		response := new(ttypes.BotMoveResponse)
		if r.YourY < 5 {
			response.MoveDirection = "up"
		} else if r.YourY > 5 {
			response.MoveDirection = "down"
		}
		// response.BroadcastMessage = fmt.Sprintf("'I am %v at %d, %d'", os.Args[0], r.YourX, r.YourY)
		responseString, err := json.Marshal(response)
		easynet.DieIfError(err, "JSON marshal error")
		conn.Write(responseString)
	}
}
예제 #4
0
파일: handshake.go 프로젝트: jingdi/go-srs
func (hs *SimpleHandshake) WithClient(conn *Conn) error {
	var iorw *net.TCPConn = conn.IoRw

	c0c1 := make([]byte, 1537)
	conn.Logger.Info("read c0c1 from conn, size=%v", len(c0c1))
	if _, err := io.ReadFull(iorw, c0c1); err != nil {
		conn.Logger.Error("read c0c1 failed, err is %v", err)
		return err
	}
	conn.Logger.Info("read c0c1 ok")

	if c0c1[0] != 0x03 {
		conn.Logger.Error("rtmp plain required 0x03, actual is %#x", c0c1[0])
		return RtmpPlainRequired
	}
	conn.Logger.Info("check rtmp plain protocol ok")

	// use bytes buffer to write content.
	s0s1s2 := bytes.NewBuffer(make([]byte, 0, 3073))

	// plain text required.
	binary.Write(s0s1s2, binary.BigEndian, byte(0x03))
	// s1 time
	binary.Write(s0s1s2, binary.BigEndian, int32(time.Now().Unix()))
	// s1 time2 copy from c1
	if _, err := s0s1s2.Write(c0c1[1:5]); err != nil {
		conn.Logger.Error("copy c0c1 time to s0s1s2 failed, err is %v", err)
		return err
	}
	// s1 1528 random bytes
	s0s1s2Random := make([]byte, 1528)
	RandomGenerate(conn.Rand, s0s1s2Random)
	if _, err := s0s1s2.Write(s0s1s2Random); err != nil {
		conn.Logger.Error("fill s1 random bytes failed, err is %v", err)
		return err
	}
	// if c1 specified, copy c1 to s2.
	// @see: https://github.com/winlinvip/simple-rtmp-server/issues/46
	if _, err := s0s1s2.Write(c0c1[1:1537]); err != nil {
		conn.Logger.Error("copy c1 to s1 failed, err is %v", err)
		return err
	}
	conn.Logger.Info("generate s0s1s2 ok, buf=%d", s0s1s2.Len())

	if written, err := iorw.Write(s0s1s2.Bytes()); err != nil {
		conn.Logger.Error("send s0s1s2 failed, written=%d, err is %v", written, err)
		return err
	}
	conn.Logger.Info("send s0s1s2 ok")

	c2 := make([]byte, 1536)
	conn.Logger.Info("read c2 from conn, size=%v", len(c2))
	if _, err := io.ReadFull(iorw, c2); err != nil {
		conn.Logger.Error("read c2 failed, err is %v", err)
		return err
	}
	conn.Logger.Info("read c2 ok")

	return nil
}
예제 #5
0
func (dc *DefaultConnector) receive(conn *net.TCPConn) ([]byte, error) {
	err := conn.SetReadDeadline(time.Now().Add(dc.config.ReadTimeout))
	if err != nil {
		return nil, err
	}

	header := make([]byte, 8)
	_, err = io.ReadFull(conn, header)
	if err != nil {
		return nil, err
	}

	decoder := NewBinaryDecoder(header)
	length, err := decoder.GetInt32()
	if err != nil {
		return nil, err
	}
	response := make([]byte, length-4)
	_, err = io.ReadFull(conn, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}
예제 #6
0
func newClientConn(ls *LeaseServer, raw *net.TCPConn) (*clientConn, error) {
	err := raw.SetKeepAlive(true)
	if err != nil {
		return nil, err
	}
	err = raw.SetNoDelay(true)
	if err != nil {
		return nil, err
	}
	ret := &clientConn{
		id:          incrementAndGet(&ls.clientIdCounter, 1),
		c:           raw,
		d:           gob.NewDecoder(raw),
		e:           gob.NewEncoder(raw),
		req:         ls.req,
		resp:        make(chan response, 20),
		ackLock:     new(sync.Mutex),
		pendingAcks: make(map[uint64]chan bool),
	}
	// send client id
	fmt.Printf("sending id %d\n", ret.id)
	idBuff := make([]byte, 8, 8)
	binary.LittleEndian.PutUint64(idBuff, ret.id)
	ret.c.Write(idBuff)
	fmt.Println("sent")
	return ret, nil
}
예제 #7
0
// Copy from WebSocket to socket and vice versa.
func proxy(local *net.TCPConn, conn *websocketConn) {
	var wg sync.WaitGroup

	wg.Add(2)

	go func() {
		_, err := io.Copy(conn, local)
		if err != nil {
			Log("error copying ORPort to WebSocket")
		}
		local.CloseRead()
		conn.Close()
		wg.Done()
	}()

	go func() {
		_, err := io.Copy(local, conn)
		if err != nil {
			Log("error copying WebSocket to ORPort")
		}
		local.CloseWrite()
		conn.Close()
		wg.Done()
	}()

	wg.Wait()
}
예제 #8
0
func (t *Listener) accept(c *net.TCPConn) {
	g := newGobConn(c)

	/*
		XXX: Maybe this handshake should be in auto, where the other side of it is
		dmsg_, err := g.Read()
		if err != nil {
			g.Close()
			return
		}
		dmsg, ok := dmsg_.(*autoDialMsg)
		if !ok {
			g.Close()
			return
		}
		if err := g.Write(&autoAcceptMsg{}); err != nil {
			g.Close()
			return
		}
	*/

	addr := x.Addr(c.RemoteAddr().String())
	t.olk.Lock()
	defer t.olk.Unlock()
	l := t.open[dmsg.ID]
	if l == nil {
		l = newAcceptLink(addr, dmsg.ID, g, listenerBroker{t})
		t.open[dmsg.ID] = l
	} else {
		l.AcceptRedial(g)
	}
}
예제 #9
0
파일: local.go 프로젝트: momaer/asocks-go
func pipeThenClose(src, dst *net.TCPConn, finishChannel chan bool) {
	defer func() {
		src.CloseRead()
		dst.CloseWrite()
		finishChannel <- true
	}()

	buf := asocks.GetBuffer()
	defer asocks.GiveBuffer(buf)

	for {
		src.SetReadDeadline(time.Now().Add(60 * time.Second))
		n, err := src.Read(buf)
		if n > 0 {
			data := buf[0:n]
			encodeData(data)
			if _, err := dst.Write(data); err != nil {
				break
			}
		}
		if err != nil {
			break
		}
	}
}
예제 #10
0
// Read from socket and write to websocket
func ReadSocket(ws *websocket.Conn, conn *net.TCPConn) {
	reader := bufio.NewReader(conn)
	var line string = ""
	for {
		if reader == nil {
			break
		}
		buffer, isPrefix, err := reader.ReadLine()
		if err != nil {
			break
		}
		// fmt.Println("ReadSocket: got", len(buffer), "bytes")
		line = line + string(buffer)
		if !isPrefix {
			// fmt.Println("Sending message to web socket:", line)
			err = websocket.Message.Send(ws, line)
			if err != nil {
				_ = conn.Close()
			}
			line = ""
		}
	}
	fmt.Println("ReadSocket exit")
	ws.Close()
}
예제 #11
0
func handle(c *net.TCPConn, config Config) {
	defer c.Close()
	// TODO c.SetTimeout(60e9)
	r := bufio.NewReaderSize(c, 4096)
	for {

		// Note that everything in this loop should proceed as fast as it can
		// so we're not blocked and can keep processing
		// so the validation, the pipeline initiated via table.Dispatch(), etc
		// must never block.

		// note that we don't support lines longer than 4096B. that seems very reasonable..
		buf, _, err := r.ReadLine()

		if nil != err {
			if io.EOF != err {
				log.Error(err.Error())
			}
			break
		}

		buf_copy := make([]byte, len(buf), len(buf))
		copy(buf_copy, buf)
		numIn.Inc(1)

		table.Dispatch(buf_copy)
	}
}
예제 #12
0
파일: consumer.go 프로젝트: araddon/kafka
func (consumer *BrokerConsumer) tryConnect(conn *net.TCPConn, tp *TopicPartition) (err error, reader *ByteBuffer) {
	var errCode int
	request := consumer.broker.EncodeConsumeRequest()
	//log.Println("offset=", tp.Offset, " ", tp.MaxSize, " ", tp.Topic, " ", tp.Partition, "  \n\t", string(request), request)
	_, err = conn.Write(request)
	if err != nil {
		if err = consumer.handleConnError(err, conn); err != nil {
			return err, nil
		}
	}

	reader = consumer.broker.readResponse(conn)
	err, errCode = reader.ReadHeader()
	if err != nil && errCode == 1 {
		log.Println("Bad Offset id, resetting?")
		// Error Code 1 means bad offsetid, we shold get a good offset, and reconnect!
		offsetVal := GetOffset(consumer.broker.hostname, tp)
		if offsetVal > 0 {
			// RECONNECT!
			log.Println("RECONNECTING !!! ", offsetVal)
			tp.Offset = offsetVal
			if err, reader = consumer.tryConnect(conn, tp); err != nil {
				return err, nil
			}
		} else {
			return err, nil
		}

	} else if err != nil {
		//log.Println("offset=", tp.Offset, " ", tp.MaxSize, " ", err.Error(), " ", request, " ", tp.Topic, " ", tp.Partition, "  \n\t", string(request))
		return err, nil
	}
	return
}
예제 #13
0
// NewClient returns new TCP client connection.
func NewClient(md *meta.Data, serverAddress string, sockerPort, providerPort int) (client *Client, err error) {
	var tcpAddr *net.TCPAddr
	tcpAddr, err = net.ResolveTCPAddr("tcp4", serverAddress)
	if err != nil {
		return
	}

	var tcpConn *net.TCPConn
	tcpConn, err = net.DialTCP("tcp", nil, tcpAddr)
	if err != nil {
		return
	}

	tcpConn.Write(append([]byte(md.UserID+"::"+strconv.Itoa(sockerPort)+"::"+strconv.Itoa(providerPort)), '\n'))

	client = &Client{
		TCPConn: tcpConn,
		close:   make(chan bool),
		ackChan: make(chan bool),
		reader:  bufio.NewReader(tcpConn),
		md:      md,
	}

	return
}
예제 #14
0
func (srvr *FileServer) serve(conn *net.TCPConn, clientID int) {
	reader := bufio.NewReader(conn)
	for {
		msg, msgerr, fatalerr := fs.GetMsg(reader)
		leader := srvr.rn.LeaderId()
		if leader != srvr.id {
			//fmt.Println(srvr.id, " : To client ID ", msg, " : Not the Leader, sending an L ")
			if leader == -1 {
				// Don't know the leader
				//fmt.Println("Do not know the current leader")
				reply(conn, &fs.Msg{Kind: 'L', Contents: []byte("ERR_REDIRECT _")})
			} else {
				content := []byte("ERR_REDIRECT " + srvr.nodeURLs[leader])
				//fmt.Println("Redirecting to correct URL : ",  srvr.nodeURLs[leader])
				reply(conn, &fs.Msg{Kind: 'L', Contents: content, Numbytes: len(content)})
			}
			break
		}

		if fatalerr != nil || msgerr != nil {
			reply(conn, &fs.Msg{Kind: 'M'})
			conn.Close()
			break
		}
		msg.ClientID = clientID
		msg.ServerID = srvr.id
		data, err := json.Marshal(msg)
		//fmt.Println("Marshalled data : ", string(data))
		check(err)
		srvr.rn.Append(data)

	}
}
예제 #15
0
파일: cbp.go 프로젝트: thraxil/cbp
func proxy(cliConn *net.TCPConn, rAddr *net.TCPAddr) error {
	srvConn, err := net.DialTCP("tcp", nil, rAddr)
	if err != nil {
		cliConn.Close()
		return err
	}
	defer srvConn.Close()

	// channels to wait on the close event for each connection
	serverClosed := make(chan struct{}, 1)
	clientClosed := make(chan struct{}, 1)

	go broker(srvConn, cliConn, clientClosed)
	go broker(cliConn, srvConn, serverClosed)

	var waitFor chan struct{}
	select {
	case <-clientClosed:
		// the client closed first
		srvConn.SetLinger(0)
		srvConn.CloseRead()
		waitFor = serverClosed
	case <-serverClosed:
		cliConn.CloseRead()
		waitFor = clientClosed
	}

	<-waitFor
	return nil
}
예제 #16
0
func readServer(pTCPConn *net.TCPConn) {
	//buffer := make([]byte, 1024)
	tempBuf := make([]byte, 4)
	for {
		bufferSize, err := pTCPConn.Read(tempBuf)
		if err != nil {
			fmt.Println("read error: ", err)
			break
		}
		if bufferSize >= 4 {
			bodyLen := BytesToInt(tempBuf)
			fmt.Println("bodyLen: ", bodyLen)
			bodyBuffer := make([]byte, bodyLen)
			_, err := pTCPConn.Read(bodyBuffer)
			if err != nil {
				fmt.Println("err : ", err)
				break
			}
			msg := &protocol.WMessage{}
			err = proto.Unmarshal(bodyBuffer, msg)
			if err != nil {
				fmt.Println("unmarshal:", err)
				return
			}
			fmt.Println("解码:", msg.String())
		}
	}
}
예제 #17
0
파일: main.go 프로젝트: aelnaiem/torronto
func sendMessage(hostName string, portNumber int, msg []byte) {
	tcpAddr, err := net.ResolveTCPAddr("tcp4", net.JoinHostPort(hostName, strconv.Itoa(portNumber)))
	checkError(err)

	var conn *net.TCPConn
	for {
		conn, err = net.DialTCP("tcp", nil, tcpAddr)
		if err != nil {
			switch e := err.(type) {
			case (*net.OpError):
				if e.Err.Error() == "connection refused" {
					return
				}
			default:
				fmt.Println(err)
			}
		} else {
			break
		}
	}

	_, err = conn.Write(msg)
	checkError(err)
	conn.Close()
	return
}
예제 #18
0
func write(conn *net.TCPConn) {

	n := protocol.Mode(5)
	reg := &protocol.WMessage{
		MsgType:   proto.String("sendMsg"),
		MsgTypeId: proto.Int32(8),
		UserInfo: &protocol.User{
			Username: proto.String("jim"),
			//Password: proto.String("123456"),
		},
		SendMsg: &protocol.SendMessage{
			Receiver: proto.String("zhang"),
			MsgType:  &n,
			Msg:      proto.String("吃了吗?"),
		},
	}
	buf, err := proto.Marshal(reg)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	fmt.Println("buf: ", len(buf))
	length := len(buf)
	buffer := append(common.IntToBytes(length), buf...)
	conn.Write(buffer)
	//return buffer
	//conn.Write(common.IntToBytes(length))
}
예제 #19
0
func (this *HttpProxyServer) handleConnection(conn *net.TCPConn) {
	defer conn.Close()
	reader := bufio.NewReader(conn)

	request, err := http.ReadRequest(reader)
	if err != nil {
		log.Warning("Failed to read http request: ", err)
		return
	}
	log.Info("Request to Method [", request.Method, "] Host [", request.Host, "] with URL [", request.URL, "]")
	defaultPort := v2net.Port(80)
	if strings.ToLower(request.URL.Scheme) == "https" {
		defaultPort = v2net.Port(443)
	}
	host := request.Host
	if len(host) == 0 {
		host = request.URL.Host
	}
	dest, err := parseHost(host, defaultPort)
	if err != nil {
		log.Warning("Malformed proxy host (", host, "): ", err)
		return
	}
	if strings.ToUpper(request.Method) == "CONNECT" {
		this.handleConnect(request, dest, reader, conn)
	} else {
		this.handlePlainHTTP(request, dest, reader, conn)
	}
}
예제 #20
0
func handleConnection(clientConn *net.TCPConn) {
	if clientConn == nil {
		log.Debugf("handleConnection(): oops, clientConn is nil")
		return
	}

	// test if the underlying fd is nil
	remoteAddr := clientConn.RemoteAddr()
	if remoteAddr == nil {
		log.Debugf("handleConnection(): oops, clientConn.fd is nil!")
		return
	}

	ipv4, port, clientConn, err := getOriginalDst(clientConn)
	if err != nil {
		log.Infof("handleConnection(): can not handle this connection, error occurred in getting original destination ip address/port: %+v\n", err)
		return
	}
	// If no upstream proxies were provided on the command line, assume all traffic should be sent directly
	if gProxyServerSpec == "" {
		handleDirectConnection(clientConn, ipv4, port)
		return
	}
	// Evaluate for direct connection
	ip := net.ParseIP(ipv4)
	if ok, _ := director(&ip); ok {
		handleDirectConnection(clientConn, ipv4, port)
		return
	}
	handleProxyConnection(clientConn, ipv4, port)
}
예제 #21
0
func handleRequest(conn *net.TCPConn, request *protocol.VMessRequest, input <-chan []byte, finish *sync.Mutex) {
	defer finish.Unlock()
	encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn)
	if err != nil {
		log.Error("VMessOut: Failed to create encrypt writer: %v", err)
		return
	}

	buffer := make([]byte, 0, 2*1024)
	buffer, err = request.ToBytes(user.NewTimeHash(user.HMACHash{}), user.GenerateRandomInt64InRange, buffer)
	if err != nil {
		log.Error("VMessOut: Failed to serialize VMess request: %v", err)
		return
	}

	// Send first packet of payload together with request, in favor of small requests.
	payload, open := <-input
	if open {
		encryptRequestWriter.Crypt(payload)
		buffer = append(buffer, payload...)

		_, err = conn.Write(buffer)
		if err != nil {
			log.Error("VMessOut: Failed to write VMess request: %v", err)
			return
		}

		v2net.ChanToWriter(encryptRequestWriter, input)
	}
	return
}
예제 #22
0
파일: tcp.go 프로젝트: huweixuan/goim
func (server *Server) serveTCP(conn *net.TCPConn, rrp, wrp *sync.Pool, rr *bufio.Reader, wr *bufio.Writer, tr *Timer) {
	var (
		b   *Bucket
		p   *Proto
		hb  time.Duration // heartbeat
		key string
		err error
		trd *TimerData
		ch  = NewChannel(Conf.CliProto, Conf.SvrProto)
		pb  = make([]byte, maxPackIntBuf)
	)
	// auth
	if trd, err = tr.Add(Conf.HandshakeTimeout, conn); err != nil {
		log.Error("handshake: timer.Add() error(%v)", err)
		goto failed
	}
	key, hb, err = server.authTCP(rr, wr, pb, ch)
	tr.Del(trd)
	if err != nil {
		log.Error("server.authTCP() error(%v)", err)
		goto failed
	}
	// register key->channel
	b = server.Bucket(key)
	b.Put(key, ch)
	// hanshake ok start dispatch goroutine
	go server.dispatchTCP(conn, wrp, wr, ch, hb, tr)
	for {
		// fetch a proto from channel free list
		if p, err = ch.CliProto.Set(); err != nil {
			log.Error("%s fetch client proto error(%v)", key, err)
			goto failed
		}
		// parse request protocol
		if err = server.readTCPRequest(rr, pb, p); err != nil {
			log.Error("%s read client request error(%v)", key, err)
			goto failed
		}
		// send to writer
		ch.CliProto.SetAdv()
		ch.Signal()
	}
failed:
	// dialog finish
	// may call twice
	if err = conn.Close(); err != nil {
		log.Error("reader: conn.Close() error(%v)")
	}
	PutBufioReader(rrp, rr)
	if b != nil {
		b.Del(key)
		log.Debug("wake up dispatch goroutine")
		ch.Finish()
	}
	if err = server.operator.Disconnect(key); err != nil {
		log.Error("%s operator do disconnect error(%v)", key, err)
	}
	log.Debug("%s serverconn goroutine exit", key)
	return
}
예제 #23
0
파일: util.go 프로젝트: safeie/nfss
// 协议封装读取
func TCPConnRead(conn *net.TCPConn) ([]byte, error) {
	conn.SetReadDeadline(time.Now().Add(time.Second * 30))
	result := bytes.NewBuffer(nil)
	data := make([]byte, 4)
	num, err := conn.Read(data)
	if err != nil || num != 4 {
		if err == nil {
			err = errors.New("length read error")
		}
		return nil, err
	}
	result.Write(data[0:num])
	var length int32
	err = binary.Read(result, binary.LittleEndian, &length)
	if err != nil {
		return nil, err
	}
	if length > MAX_PACKET_SIZE {
		return nil, errors.New("too large packet! packet size should less than 1M")
	}
	data = make([]byte, length)
	result = bytes.NewBuffer(nil)
	num, err = io.ReadFull(conn, data)
	if err != nil {
		return nil, err
	}
	result.Write(data[0:num])
	return result.Bytes(), nil
}
예제 #24
0
func handleConnWithBufferio(conn *net.TCPConn, req_conn *net.TCPConn, sid string, worker_idf string) {

	// 发包频率判断
	range_count := 1
	limit_date := global.Config.Connector.MaxPacketRate
	var now int64
	var start_time int64
	var range_times int64
	start_time = time.Now().Unix()
	range_times = int64(global.Config.Connector.MaxPacketRateUnit)

	//声明一个管道用于接收解包的数据
	reader := bufio.NewReader(conn)
	for {
		if !global.Config.Enable {
			conn.Write([]byte(fmt.Sprintf("%s\r\n", global.DISBALE_RESPONSE)))
			conn.Close()
			break
		}

		// 区间范围内的计数
		if limit_date > 0 {
			now = time.Now().Unix()
			if (now - start_time) <= range_times {
				range_count++
			} else {
				start_time = now
				range_count = 1
			}
			// 判断发包频率是否超过限制
			if range_count > limit_date {
				conn.Write([]byte(global.ERROR_PACKET_RATES + "\n"))
				conn.Close()
				break
			}
		}

		msg, err := reader.ReadString('\n')
		//fmt.Println(  "handleConn ReadString: ", string(msg) )
		if err != nil {
			CloseConn(conn, sid)
			//fmt.Println( "HandleConn connection error: ", err.Error())
			break
		}
		if msg == "" {
			continue
		}
		go func(sid string, msg string, req_conn *net.TCPConn) {

			// fmt.Println(conn.RemoteAddr().String(), "receive str:", string(msg) )
			worker_idf := GetRandWorkerIdf()
			worker_data := fmt.Sprintf(`%s||%s||%s||%s`, global.DATA_REQ_MSG, sid, worker_idf, msg)
			//fmt.Println("req push worker_data 2:", worker_data)
			req_conn.Write([]byte(worker_data + "\n"))

		}(sid, msg, req_conn)

	}

}
예제 #25
0
파일: command.go 프로젝트: jmptrader/Caesar
func Service(conn *net.TCPConn) {
	b := make([]byte, 1024)
	for {
		lenth, _ := conn.Read(b)
		DisCmd(string(b[:lenth]))
	}
}
예제 #26
0
func (this *DelayProxy) tcpForward(src *net.TCPConn, dest *net.TCPConn, finishedChan chan int) {
	var err error
	var n int
	var buffer = make([]byte, CHUNK_SIZE)

	for {
		n, err = src.Read(buffer)
		if n < 1 {
			break
		}

		if err != nil {
			Logf("%s: read error: %d %s\n", this.id, n, err)
			break
		}

		Sleep(this.transferDelay)

		n, err = dest.Write(buffer[0:n])
		if n < 1 {
			break
		}

		if err != nil {
			Logf("%s: write error: %d %s\n", this.id, n, err)
			break
		}
	}

	finishedChan <- 1
}
예제 #27
0
파일: peers.go 프로젝트: aelnaiem/torronto
func (peers *Peers) connectPeer(hostName string, portNumber int, conn *net.TCPConn) {
	peer, err := peers.getPeer(hostName, portNumber)
	checkError(err)

	err = conn.SetReadBuffer(ChunkSize)
	checkError(err)

	readBuffer := make([]byte, ChunkSize)
	_, err = conn.Read(readBuffer)
	checkError(err)

	var fileList FileList
	readBuffer = bytes.TrimRight(readBuffer, "\x00")

	err = json.Unmarshal(readBuffer, &fileList)
	checkError(err)

	if peer.currentState != Connected {
		updateStatus(hostName, portNumber, fileList.Files)
		peers.numPeers += 1
	}

	peer.currentState = Connected
	return
}
예제 #28
0
파일: router.go 프로젝트: adieu/weave
func (router *Router) acceptTCP(tcpConn *net.TCPConn) {
	// someone else is dialing us, so our udp sender is the conn
	// on Port and we wait for them to send us something on UDP to
	// start.
	connRemote := NewRemoteConnection(router.Ourself, nil, tcpConn.RemoteAddr().String())
	NewLocalConnection(connRemote, UnknownPeerName, tcpConn, nil, router)
}
예제 #29
0
파일: deploy.go 프로젝트: vjeko/godrone
func write(conn *net.TCPConn, cmd string) {
	cmd = fmt.Sprintf("%s\n", cmd)
	_, err := conn.Write([]byte(cmd))
	if err != nil {
		panic(err)
	}
}
예제 #30
0
파일: main.go 프로젝트: runningwild/barbu
func handleHost(conn *net.TCPConn) {
	defer conn.Close()
	defer fmt.Printf("Closed host conn.\n")

	w := bufio.NewWriter(conn)

	name_line := make([]byte, 32)
	n, err := conn.Read(name_line)
	if err != nil {
		// TODO: Log this error
		fmt.Printf("Failed to read game from host: %v\n", err)
		return
	}
	name := strings.TrimSpace(string(name_line[0:n]))
	fmt.Printf("Game name: '%s': %d\n", name, len(name))
	if !registerGame(name, conn) {
		w.Write([]byte(fmt.Sprintf("Unable to make game '%s', that name is already in use.\n", name)))
		return
	}
	defer unregisterGame(name)
	w.Flush()

	game := getGame(name)
	game.Run()
}