Beispiel #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))
			}
		}
	}
}
Beispiel #2
0
func serve(conn *net.TCPConn, fileS *File_Server, uid int) {
	reader := bufio.NewReader(conn)
	for {
		msg, msgerr, fatalerr := fs.GetMsg(reader)
		if fatalerr != nil || msgerr != nil {
			reply(conn, &fs.Msg{Kind: 'M'})
			conn.Close()
			break
		}
		if msgerr != nil {
			if (!reply(conn, &fs.Msg{Kind: 'M'})) {
				conn.Close()
				break
			}
		}
		newchannel := make(chan *fs.Msg, 1)
		mutex.Lock()
		fileS.Msgcount = fileS.Msgcount + 1
		count := fileS.Msgcount
		fileS.Channels[count] = newchannel
		fmt.Println("Listening at", count)
		mutex.Unlock()
		modified_msg := Message{uid, count, *msg} // We are adding message id with it.
		newmsg, _ := json.Marshal(modified_msg)
		fileS.Raft.Append(newmsg)

		for {
			select {
			case ci := <-fileS.Channels[count]:
				reply(conn, ci)
			}
			break
		}
	}
}
Beispiel #3
0
// Handles connections to a service and calls the handler specified in RunService().
func handleServiceConnection(connection *net.TCPConn, handler ServiceHandler) error {
	servicecall := ServiceCall{}
	buffer := make([]byte, PACKET_SIZE)

	defer connection.Close()

	length, err := connection.Read(buffer)
	if err != nil {
		return err
	}
	err = json.Unmarshal(buffer[:length], &servicecall)
	if err != nil {
		return err
	}

	ret := handler(&servicecall)

	bytes, err := json.Marshal(ServiceResult{ret})
	if err != nil {
		return err
	}
	_, err = connection.Write(bytes)
	if err != nil {
		return err
	}

	return nil
}
Beispiel #4
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)
	}
}
Beispiel #5
0
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
}
func handleConnection(conn *net.TCPConn) error {
	defer conn.Close()

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

	var ws *websocket.Conn

	conn.SetDeadline(time.Now().Add(socksTimeout))
	err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
		// Disable deadline.
		conn.SetDeadline(time.Time{})
		Log("SOCKS request for %s", dest)
		destAddr, err := net.ResolveTCPAddr("tcp", dest)
		if err != nil {
			return nil, err
		}
		wsUrl := url.URL{Scheme: "ws", Host: dest}
		ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
		if err != nil {
			return nil, err
		}
		Log("WebSocket connection to %s", ws.Config().Location.String())
		return destAddr, nil
	})
	if err != nil {
		return err
	}
	defer ws.Close()
	proxy(conn, ws)
	return nil
}
Beispiel #7
0
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
}
Beispiel #8
0
// serve serves a single accepted connection
func (p *proxy) serve(client *net.TCPConn) {
	connected := connectedClients.With(p.labels)
	connected.Inc()

	defer func() {
		connected.Dec()
		_ = client.Close()
	}()

	p.mutex.Lock()
	upstreams := make([]Upstream, len(p.upstreams))
	copy(upstreams, p.upstreams)
	p.mutex.Unlock()

	// TODO: proper iterator accounting weights and current # of connections
	for i := range upstreams {
		j := rand.Intn(i + 1)
		upstreams[i], upstreams[j] = upstreams[j], upstreams[i]
	}

	for _, upstream := range upstreams {
		p.log(fmt.Sprintf("connecting from %s to %s", client.RemoteAddr(), upstream))
		backend, err := net.Dial("tcp", upstream.Addr())
		if err != nil {
			p.log(fmt.Sprintf("error connecting from %s to %s: %s", client.RemoteAddr(), upstream.Addr(), err))
			connectionErrors.With(prometheus.Labels{"app": p.app, "upstream": upstream.Addr()}).Inc()
			continue
		}

		p.proxyLoop(client, backend.(*net.TCPConn))

		break
	}
}
Beispiel #9
0
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()
}
Beispiel #10
0
func (proxy *Proxy) handleConnection(in *net.TCPConn) error {
	defer in.Close()

	plainOut, err := proxy.connectionFactory()
	if err != nil {
		log.Print("could no create outgoing connection", err)
		return err
	}
	out := plainOut.(*net.TCPConn)
	defer out.Close()

	serverClosed := make(chan struct{}, 1)
	clientClosed := make(chan struct{}, 1)

	go broker(out, in, clientClosed)
	go broker(in, out, serverClosed)

	var waitFor chan struct{}

	select {
	case <-clientClosed:
		// the client closed first and any more packets from the server aren't
		// useful, so we can optionally SetLinger(0) here to recycle the port
		// faster.
		out.SetLinger(0)
		out.CloseRead()
		waitFor = serverClosed
	case <-serverClosed:
		in.CloseRead()
		waitFor = clientClosed
	}

	<-waitFor
	return nil
}
Beispiel #11
0
func handleClient(pf *PF, source *net.TCPConn) {
	atomic.AddInt32(&pf.status.actives, 1)
	defer func() {
		atomic.AddInt32(&pf.status.actives, -1)
		pf.wg.Done()
	}()

	settings := pf.settings
	host := chooseHost(settings.weight, settings.Hosts)
	if host == nil {
		source.Close()
		logger.Println("choose host failed")
		return
	}

	dest, err := net.DialTCP("tcp", nil, host.addr)
	if err != nil {
		source.Close()
		logger.Printf("connect to %s failed: %s", host.addr, err.Error())
		return
	}

	source.SetKeepAlive(true)
	source.SetKeepAlivePeriod(time.Second * 60)
	source.SetLinger(-1)
	dest.SetLinger(-1)

	go forward(source, dest)
	forward(dest, source)
	//logger.Printf("forward finished, %v -> %v", source.RemoteAddr(), host)
}
Beispiel #12
0
func forward(source *net.TCPConn, dest *net.TCPConn) {
	defer func() {
		dest.Close()
	}()

	bufsz := 1 << 12
	cache := make([]byte, bufsz)
	for {
		// pump from source
		n, err1 := source.Read(cache)

		// pour into dest
		c := 0
		var err2 error
		for c < n {
			i, err2 := dest.Write(cache[c:n])
			if err2 != nil {
				break
			}
			c += i
		}

		if err1 != nil || err2 != nil {
			break
		}
	}
}
Beispiel #13
0
// Demo goroutine start, but main goroutine exit, which kills the connection.
// Not useful, but indicates how connections work.
// 'Tested' using 'telnet localhost 45678'
func getData(tcpConn *net.TCPConn, done chan bool) {
	for {
		var buffer = make([]byte, 256)
		fmt.Println("Starting Read ...")
		bytesRead, err := tcpConn.Read(buffer)
		if err != nil {
			fmt.Printf("Error = %v\n", err)
			break
		}
		//
		fmt.Println("Bytes Read", tcpConn, bytesRead)
		bufData := buffer[0:bytesRead]
		fmt.Println("Buffer", tcpConn, bufData)
		var data = string(bufData)
		fmt.Println("Data Read", tcpConn, data)
		//
		if strings.HasPrefix(data, "quit") {
			break
		}
	}
	//
	fmt.Println("Starting Close() 1")
	err := tcpConn.Close()
	if err != nil {
		fmt.Printf("Error = %v\n", err)
		panic("wtf05")
	}
	//
	done <- true
}
Beispiel #14
0
func serve(con *net.TCPConn) {

	defer con.Close()

	if *verbose {
		fmt.Fprintf(os.Stdout, "serving %s\n", con.RemoteAddr().String())
	}

	for {

		line, err := readUntilCrLf(con)

		if err != nil {
			// TODO : pass error message
			con.Write([]byte("\"internal error\"\r\n"))
			continue
		}

		tokens := strings.Split(string(line), " ", -1)

		command := tokens[0]

		if command == "quit" {
			writeJson(con, "bye.")
			break
		}

		f, ok := commands[command]
		if ok {
			f(con, tokens[1:])
		} else {
			writeJson(con, fmt.Sprintf("unknown command '%s'", command))
		}
	}
}
Beispiel #15
0
func ReadTCPChannel(conn *net.TCPConn, delimiter string, fromSocket chan Message) error {
	var message string
	buffer := make([]byte, socketBuffer)

	for {
		if n, err := conn.Read(buffer); err != nil || n == 0 {
			if n == 0 && err == nil {
				err = errors.New("No bytes")
			}
			myLog.Printf("Closing:%v %v\n", conn.RemoteAddr(), err)
			conn.Close()
			return err
		} else {

			message += string(buffer[0:n])

			m := strings.Split(message, delimiter)
			for i, entry := range m {
				if i < len(m)-1 {
					fromSocket <- Message{Msg: entry, RemoteAddr: conn.RemoteAddr()}
				} else {
					// overflow
					message = entry
				}
			}
		}

	}
	return nil
}
Beispiel #16
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()
}
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)
	}
}
Beispiel #18
0
func onNewConn(source *net.TCPConn, req *NewConnReq) {
	settings := daemon.settings
	host := chooseHost(settings.weight, settings.Hosts)
	if host == nil {
		source.Close()
		Error("choose host failed:%v", source.RemoteAddr())
		return
	}

	dest, err := net.DialTCP("tcp", nil, host.addr)
	if err != nil {
		source.Close()
		Error("connect to %s failed: %s", host.addr, err.Error())
		return
	}

	dest.SetKeepAlive(true)
	dest.SetKeepAlivePeriod(time.Second * 60)
	dest.SetLinger(-1)

	id := <-daemon.nextidCh
	link := NewStableLink(id, source, dest, req.key)
	daemon.eventCh <- link
	link.Run()
	daemon.eventCh <- link
	link.Wait()
}
Beispiel #19
0
// Read TCP socket and return complete ByteMessage to caller's channel
func ReadTCPChannel(conn *net.TCPConn, delimiter []byte, fromSocket chan ByteMessage) error {
	var message []byte
	buffer := make([]byte, SocketBuffer)

	for {
		if n, err := conn.Read(buffer); err != nil || n == 0 {
			if n == 0 && err == nil {
				err = errors.New("No bytes")
			}
			Logger.Println("Closing read:", conn.RemoteAddr(), err)
			conn.Close()
			return err
		} else {

			message = append(message, buffer[0:n]...)
			m := bytes.Split(message, delimiter)
			for i, entry := range m {
				if i < len(m)-1 {
					fromSocket <- ByteMessage{Msg: entry, RemoteAddr: conn.RemoteAddr()}
				} else {
					// overflow
					message = entry
				}
			}
		}

	}
	return nil
}
Beispiel #20
0
func (s *Service) handleConnection(conn *net.TCPConn) {
	defer conn.Close()
	defer s.wg.Done()

	controller := controller.NewSession(conn, s.repo)
	defer controller.FinishSession()

	for {
		select {
		case <-s.ch:
			log.Println("disconnecting", conn.RemoteAddr())
			return
		default:
		}
		err := controller.Dispatch()
		if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
			continue
		}
		if err != nil {
			if err.Error() != "EOF" {
				log.Println(conn.RemoteAddr(), err)
			}
			return
		}
	}
}
Beispiel #21
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)

	}

}
Beispiel #22
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)

	}
}
Beispiel #23
0
func (peer Peer) downloadFile(file File, conn *net.TCPConn) {
	if f, ok := status.status["local"].files[file.FileName]; ok {
		if f.Chunks[file.Chunks[1]] == 1 {
			return
		}
	} else {
		chunks := make([]int, file.Chunks[0])
		for chunk := range chunks {
			chunks[chunk] = 0
		}
		chunks[file.Chunks[1]] = 1
		status.status["local"].files[file.FileName] = File{
			FileName: file.FileName,
			Chunks:   chunks,
		}
	}
	status.status["local"].files[file.FileName].Chunks[file.Chunks[1]] = 1
	incrementChunkReplication(file.FileName, file.Chunks[1], file.Chunks[0])

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

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

	status.mu.Lock()
	basepath := path.Dir(file.FileName)
	fileName := path.Base(file.FileName)
	err = os.MkdirAll(basepath, 0777)
	checkError(err)

	filePath := path.Join(basepath, fileName)

	localFile, err := os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0777)
	if err != nil {
		for {
			localFile, err = os.OpenFile(filePath, os.O_CREATE|os.O_RDWR, 0777)
			if err == nil {
				break
			}
		}
	}

	writeOffset := int64(file.Chunks[1] * ChunkSize)
	_, err = localFile.WriteAt(bytes.TrimRight(readBuffer, "\x00"), writeOffset)
	checkError(err)

	err = localFile.Close()
	checkError(err)

	status.mu.Unlock()
	fmt.Printf("Downloaded file %s:%d \n\n", file.FileName, file.Chunks[1])

	fileList := []File{file}
	haveMessage := encodeMessage(peer.host, peer.port, Have, fileList)
	sendToAll(haveMessage)
	return
}
Beispiel #24
0
func handleConnection(conn *net.TCPConn, no_delay int, packet_bytes int) {
	defer conn.Close()
	fmt.Println("handle connection", conn)

	if no_delay == 0 {
		if err := conn.SetNoDelay(false); err != nil {
			fmt.Println("set no delay to false failed.")
			return
		}
		fmt.Println("set no delay to false ok.")
	}

	/*SO_SNDBUF := 16384
	  if err := conn.SetWriteBuffer(SO_SNDBUF); err != nil {
	      fmt.Println("set send SO_SNDBUF failed.")
	      return
	  }
	  fmt.Println("set send SO_SNDBUF to", SO_SNDBUF, "ok.")*/

	b := make([]byte, packet_bytes)
	fmt.Println("write", len(b), "bytes to conn")

	for {
		n, err := conn.Write(b)
		if err != nil {
			fmt.Println("write data error, n is", n, "and err is", err)
			break
		}
	}
}
Beispiel #25
0
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
}
Beispiel #26
0
func RunTelnet(ws *websocket.Conn, conn *net.TCPConn) {
	fmt.Println("Running telnet")
	go ReadSocket(ws, conn)

	// Read websocket and write to socket.
	crlf := []byte{13, 10}
	var msg string
	for {
		err := websocket.Message.Receive(ws, &msg)
		if err != nil {
			_ = conn.Close()
			break
		}
		_, err = conn.Write([]byte(msg))
		if err != nil {
			break
		}
		fmt.Println("Sent message to host:", msg)
		// Send \r\n (as HTTP protocol requires)
		_, err = conn.Write(crlf)
		if err != nil {
			break
		}
	}
	fmt.Println("RunTelnet exit")
}
Beispiel #27
0
func tcpShim(inbound, outbound *net.TCPConn, connEvent *events.Connection, eh events.Handler) error {
	eh.Connection(connEvent)
	ch := make(chan error, 1)
	go func() {
		var err error
		defer func() { ch <- err }()
		_, err = io.Copy(inbound, outbound)
		outbound.CloseRead()
		inbound.CloseWrite()
	}()

	_, err1 := io.Copy(outbound, inbound)
	inbound.CloseRead()
	outbound.CloseWrite()

	err2 := <-ch
	inbound.Close()
	outbound.Close()

	if err1 != nil {
		return err1
	} else {
		return err2
	}
}
Beispiel #28
0
// 分配连接处理
func (self *AgentSvr) handleConnection(conn *net.TCPConn) {
	defer conn.Close()
	defer self.wg.Done()
	defer func() {
		if err := recover(); err != nil {
			Error("handle agent connection:%v failed:%v", conn.RemoteAddr(), err)
		}
	}()

	Info("new agent connection:%v", conn.RemoteAddr())
	for {
		var sz uint32
		err := binary.Read(conn, binary.BigEndian, &sz)
		if err != nil {
			Error("read conn failed:%v, err:%v", conn.RemoteAddr(), err)
			break
		}
		buf := make([]byte, sz)
		_, err = io.ReadFull(conn, buf)
		if err != nil {
			Error("read conn failed:%v, err:%v", conn.RemoteAddr(), err)
			break
		}
		var req Request
		if err = json.Unmarshal(buf, &req); err != nil {
			Error("parse request failed:%v, err:%v", conn.RemoteAddr(), err)
		}

		go self.dispatchRequst(conn, &req)
	}
}
Beispiel #29
0
func handleClient(conn *net.TCPConn) {
	defer func() {
		log.Printf("Disconnect from %v", conn.RemoteAddr())
		conn.Close()
		connectionsM.Lock()
		delete(connections, conn.RemoteAddr().String())
		connectionsM.Unlock()
	}()

	log.Printf("Connect from %v", conn.RemoteAddr())

	buf := make([]byte, 1024)
	for {
		n, err := conn.Read(buf)
		if n > 0 {
			messages <- Message{conn, string(buf[:n])}
		}
		if err != nil {
			if err != io.EOF {
				log.Printf("Error from %v: %s", conn.RemoteAddr(), err)
			}
			return
		}
	}
}
Beispiel #30
-1
func read_tcp_conn(tcpConn *net.TCPConn, connChan chan []byte) {

	buffer := make([]byte, 2048)

	tcpConn.SetReadBuffer(2048)

	for {

		n, err := tcpConn.Read(buffer[0:])

		if err != nil {

			log.Println("one tcp connection read function failed!")

			log.Println("one tcp connection close now!")

			tcpConn.Close()

			runtime.Goexit()

		} else {

			connChan <- buffer[0 : n-1]

		}

	}

}