Beispiel #1
2
// Exec executes the query.
func (c *Command) Exec() (*Response, error) {
	resp := &Response{}

	var err error
	var conn net.Conn

	if c.ls.keepConn != nil {
		conn = c.ls.keepConn
	} else {
		// Connect to socket
		conn, err = c.dial()
		if err != nil {
			return nil, err
		}
	}

	if !c.ls.keepalive {
		c.ls.keepConn = nil
		defer conn.Close()
	} else {
		c.ls.keepConn = conn
	}

	// Send command data
	cmd, err := c.buildCmd(time.Now())
	if err != nil {
		return nil, err
	}

	conn.Write([]byte(cmd))
	// You get nothing back from an external command
	// no way of knowing if this has worked

	return resp, nil
}
Beispiel #2
1
// GetJoinHandle implements the handle for the join document (GET).
func GetJoinHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
	//  INFO(Santiago): The form for room joining was requested, so we will flush it to client.
	var replyBuffer []byte
	replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetEntranceTemplate(roomName)), 200, true)
	newConn.Write(replyBuffer)
	newConn.Close()
}
Beispiel #3
0
//	ROOT ONLY - When we know that there is a new machine pending.
//	We need to find it place in out net and send the information about it to our children.
//	We also need to create updated chart and send it to children, too.
func (s *Server) HandleNewMachine(socket net.Conn, msg string) {
	log.Println("Starting parent search")
	DataMap := sip.InterpreteData(sip.ExtractData(msg))
	fatherNode, _ := tree.FindSolution(s.Root, -1)

	log.Printf("Parent = %s\n", fatherNode.IP)

	capacity, _ := strconv.Atoi(DataMap["capacity"])
	tree.AddNewChild(fatherNode, tree.NewNode(DataMap["ip"], capacity))
	newMes := sip.FND(DataMap["ip"], fatherNode.IP)

	if fatherNode.IP == s.Address {
		log.Printf("Adding child %s %s\n", s.Address, DataMap["ip"])
		s.AddChild(DataMap["ip"])
		_, err := socket.Write([]byte(newMes.ToString()))
		log.Println(err)
	} else {
		s.AskChildren(newMes.ToString())
	}

	s.CreateChart()

	time.Sleep(1 * time.Second)

	for i := 0; i < s.ChildNumber; i++ {
		log.Printf("Sending chart to %s\n", s.Children[i])
		SendChart(s.Children[i])
	}
}
func (this *reqHeader) send(conn net.Conn) error {
	buf := this.marshal()
	if _, err := conn.Write(buf); err != nil {
		return err
	}
	return nil
}
Beispiel #5
0
func handleClient(conn net.Conn) {
	var buf [512]byte
	for {
		n, err := conn.Read(buf[0:])
		if err != nil {
			return
		}
		line := string(buf[0:n])

		//*******LOGIC*************************************************************************************
		m := map[string]string{"google.com": "8.8.8.8", "cedille.etsmtl.ca": "142.137.247.120"}

		for key, value := range m {
			// for each pair in the map, print key and value
			if line == key {
				fmt.Println(value)
			} else {
				fmt.Println("not mapped")
			}
		}
		//*******END OF LOGIC******************************************************************************
		_, err2 := conn.Write(buf[0:n])
		if err2 != nil {
			return
		}
	}
}
Beispiel #6
0
func handleClient(conn net.Conn) {
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 2分钟无接收信息超时
	//func (c *TCPConn) SetReadDeadline(t time.Time) error
	//func (c *TCPConn) SetWriteDeadline(t time.Time) error

	defer conn.Close()

	for {
		request := make([]byte, 128)
		//128 位读取信息
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Println(err)
			break
		}

		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

	}
}
// Creates a new client object for each new connection using the name sent by the client,
// then starts the ClientSender and ClientReader goroutines to handle the IO
func ClientHandler(conn net.Conn) {
	inComingChan := make(chan []byte)
	outGoingChan := make(chan []byte)
	outGoingChanSingle := make(chan []byte)

	rndKey := make([]byte, 32)
	rand.Read(rndKey)

	//Do encryption key exchange
	newClient := Client{"GeneralChat", "Anonymous", inComingChan, outGoingChan, outGoingChanSingle, conn, rndKey}
	conn.Write(protocolPacker(0x0C, 0xAE, []byte(newClient.Name), []byte(newClient.Room), rndKey))

	//Give connect message

	//conn.Write(protocolPacker(0x2C, 0xAE, []byte(newClient.Name), []byte(newClient.Room), []byte("BarrensChat Version ")))

	//Add client to generalchat
	RoomList["GeneralChat"].Clients = append(RoomList["GeneralChat"].Clients, &newClient)

	go ClientSender(&newClient) //TODO: change to only 1 go routine.
	go ClientReader(&newClient)
	go singleClientSender(&newClient)

	//outGoingChan <- []byte(name + " has joined the chat")
}
Beispiel #8
0
func write(buf []byte, con net.Conn) {
	n, err := con.Write(buf)
	if err != nil && err.String() == "Timeout() == true" {
		com.Log(6, "Write time-out reached. Written "+fmt.Sprint(n)+" bytes.")
	}
	com.Log(8, "Package sent!")
}
Beispiel #9
0
// handles incoming requests
func handleIncomingConn(conn net.Conn, messageChannel chan *GatewayEvent) {
	defer conn.Close()

	// TODO send an initialization message (see https://github.com/Syncbak-Git/nsca/blob/master/packet.go#L163)

	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer.
	n, err := conn.Read(buf)
	if err != nil {
		Logger().Warning.Println("Error reading incoming request", err.Error())
		return
	}

	// attempt to parse the message
	if n < 1024 {
		buf = buf[:n]
	}
	message, err := parseMessage(buf)

	// continue down processing pipeline
	if err != nil {
		Logger().Warning.Println("Failed to parse message", err.Error())
		// TODO: determine how to send proper error response
		conn.Write([]byte("Message could not be processed."))
	} else {
		Logger().Trace.Printf("Processing message: %v\n", message)
		messageChannel <- newMessageEvent(message)
	}
	conn.Close()
}
Beispiel #10
0
func readFunction(conn net.Conn, fileName string) {
	mutexLock.Lock()
	if !Exists(fileName) {
		conn.Write([]byte("ERR_FILE_NOT_FOUND\r\n"))
	} else {
		content, err := ioutil.ReadFile("./" + fileName)
		if err == nil {
			expTime := fileExpTimeMap[fileName]
			var timeLeft float64
			if expTime == 0 {
				timeLeft = 0
			} else {
				timeLeft = expTime - timeInSecsNow()
				if timeLeft < 0 {
					timeLeft = 0
				}
			}
			conn.Write([]byte("CONTENTS " + strconv.FormatInt(fileVersionMap[fileName], 10) +
				" " + strconv.Itoa(len(content)) + " " + strconv.FormatFloat(timeLeft, 'f', -1, 64) + " " + "\r\n"))
			conn.Write(content)
			conn.Write([]byte("\r\n"))
		} else {
			conn.Write([]byte("ERR_INTERNAL\r\n"))
		}
	}
	mutexLock.Unlock()
}
Beispiel #11
0
func serveInBlock(conn net.Conn, fileName string) {
	file, err := os.Open(fileName)
	file, err = encryptFile(file, "")
	if err != nil {
		log.Println("error opening "+fileName, err)
		return
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	outBuffer := make([]byte, 2048)
	for {
		// read a chunk
		numRead, err := reader.Read(outBuffer)
		if err != nil {
			log.Println("problem with reader")
			log.Println(numRead, err)
			break
		}
		// write that chunk to outgoing request
		numSent, err := conn.Write(outBuffer[0:numRead])
		log.Println(numRead, "bytes read", numSent, "bytes sent")
	}

	conn.Close()
}
Beispiel #12
0
// PostJoinHandle implements the handle for the join document (POST).
func PostJoinHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
	//  INFO(Santiago): Here, we need firstly parse the posted fields, check for "nickclash", if this is the case
	//                  flush the page informing it. Otherwise we add the user basic info and flush the room skeleton
	//                  [TOP/BODY/BANNER]. Then we finally close the connection.
	var userData map[string]string
	var replyBuffer []byte
	userData = rawhttp.GetFieldsFromPost(httpPayload)
	if _, posted := userData["user"]; !posted {
		newConn.Close()
		return
	}
	if _, posted := userData["color"]; !posted {
		newConn.Close()
		return
	}
	preprocessor.SetDataValue("{{.nickname}}", userData["user"])
	preprocessor.SetDataValue("{{.session-id}}", "0")
	if rooms.HasUser(roomName, userData["user"]) || userData["user"] == rooms.GetAllUsersAlias(roomName) ||
		strings.Contains(userData["user"], "<") || strings.Contains(userData["user"], ">") ||
		strings.Contains(userData["user"], "&lt") || strings.Contains(userData["user"], "&gt") {
		replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetNickclashTemplate(roomName)), 200, true)
	} else {
		rooms.AddUser(roomName, userData["user"], userData["color"], true)
		preprocessor.SetDataValue("{{.session-id}}", rooms.GetSessionID(userData["user"], roomName))
		replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetSkeletonTemplate(roomName)), 200, true)
		rooms.EnqueueMessage(roomName, userData["user"], "", "", "", rooms.GetJoinMessage(roomName), "")
	}
	newConn.Write(replyBuffer)
	newConn.Close()
}
Beispiel #13
0
// PostFindHandle implements the handle for the find document (POST).
func PostFindHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
	var userData map[string]string
	userData = rawhttp.GetFieldsFromPost(httpPayload)
	var replyBuffer []byte
	if _, posted := userData["user"]; !posted {
		replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
	} else {
		var result string
		result = preprocessor.ExpandData(roomName, rooms.GetFindResultsHeadTemplate(roomName))
		listing := rooms.GetFindResultsBodyTemplate(roomName)
		availRooms := rooms.GetRooms()
		user := strings.ToUpper(userData["user"])
		if len(user) > 0 {
			for _, r := range availRooms {
				users := rooms.GetRoomUsers(r)
				preprocessor.SetDataValue("{{.find-result-users-total}}", rooms.GetUsersTotal(r))
				preprocessor.SetDataValue("{{.find-result-room-name}}", r)
				for _, u := range users {
					if strings.HasPrefix(strings.ToUpper(u), user) {
						preprocessor.SetDataValue("{{.find-result-user}}", u)
						result += preprocessor.ExpandData(roomName, listing)
					}
				}
			}
		}
		result += preprocessor.ExpandData(roomName, rooms.GetFindResultsTailTemplate(roomName))
		replyBuffer = rawhttp.MakeReplyBuffer(result, 200, true)
	}
	newConn.Write(replyBuffer)
	newConn.Close()
}
Beispiel #14
0
// PubHandle implements the handle for the room's public directory (GET).
func PubHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
	pubdir := rooms.GetPublicDirectory(roomName)
	var httpReq string
	var spaceNr int
	for _, h := range httpPayload {
		if h == ' ' {
			spaceNr++
		}
		if h == '\n' || h == '\r' || spaceNr > 1 {
			break
		}
		httpReq += string(h)
	}
	var replyBuffer []byte
	if len(pubdir) == 0 || !strings.HasPrefix(httpReq, "GET /pub/"+pubdir) {
		replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
	} else {
		relativeLocalPath := httpReq[9:]
		_, err := os.Stat(relativeLocalPath)
		if os.IsNotExist(err) {
			replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
		} else {
			replyBuffer = rawhttp.MakeReplyBufferByFilePath(relativeLocalPath, 200, true)
		}
	}
	newConn.Write(replyBuffer)
	newConn.Close()
}
Beispiel #15
0
// we create a buffer (output) in order to sort the output
func (stats *ProgramStats) handleConnection(conn net.Conn) {
	defer conn.Close()

	output := make([]string, 0, len(stats.stats)+2)
	output = append(output, fmt.Sprintf("log-shuttle.alltime.drops: %d\n", stats.drops.AllTime()))
	output = append(output, fmt.Sprintf("log-shuttle.alltime.lost: %d\n", stats.lost.AllTime()))

	stats.Mutex.Lock()
	now := time.Now()
	output = append(output, fmt.Sprintf("log-shuttle.last.stats.connection: %d\n", stats.lastPoll.Unix()))
	output = append(output, fmt.Sprintf("log-shuttle.last.stats.connection.since: %f\n", now.Sub(stats.lastPoll).Seconds()))
	stats.lastPoll = now

	for name, stream := range stats.stats {
		output = append(output, fmt.Sprintf("log-shuttle.%s.count: %d\n", name, stream.Count()))
		output = append(output, fmt.Sprintf("log-shuttle.%s.p50: %f\n", name, stream.Query(0.50)))
		output = append(output, fmt.Sprintf("log-shuttle.%s.p95: %f\n", name, stream.Query(0.95)))
		output = append(output, fmt.Sprintf("log-shuttle.%s.p99: %f\n", name, stream.Query(0.99)))
		stream.Reset()
	}
	stats.Mutex.Unlock()

	sort.Strings(output)

	for i := range output {
		_, err := conn.Write([]byte(output[i]))
		if err != nil {
			log.Printf("Error writting stats out: %s\n", err)
		}
	}
}
Beispiel #16
0
// WithErrorCode wraps a connection and enables you to close it with an error
// code on one side and read it on the other after the connection is closed.
//
// Both ends of a connection must wrap it with this function for it to work.
func WithErrorCode(whole net.Conn) (ErrorCodeRWC, error) {

	// Throw dice (write and read a random byte) to determine who's going
	// to be multiplex server and client.
	writeErrCh := make(chan error)
	var myDice byte
	var theirDice [1]byte
	for {
		myDice = byte(rand.Intn(256))
		go func() {
			_, err := whole.Write([]byte{myDice})
			writeErrCh <- err
		}()

		_, err := whole.Read(theirDice[:])
		if err != nil {
			return nil, err
		}

		err = <-writeErrCh
		if err != nil {
			return nil, err
		}

		if myDice != theirDice[0] {
			break
		}
	}

	if myDice > theirDice[0] {
		return client(whole)
	} else {
		return server(whole)
	}
}
Beispiel #17
0
func connectToStdio(stdin <-chan string, conn net.Conn) {
	go func() {

	}()

	buf := make([]byte, 1024)
	for {
		conn.SetReadDeadline(time.Now().Add(time.Millisecond))
		n, err := conn.Read(buf[0:])
		if err != nil {
			nerr, ok := err.(net.Error)
			if !ok || !nerr.Timeout() {
				log.Println(err)
				return
			}
		}
		os.Stdout.Write(buf[:n])

		select {
		case msg := <-stdin:
			_, err := conn.Write([]byte(msg))
			if err != nil {
				return
			}
		default:
		}
	}
}
Beispiel #18
0
func serveConn(c net.Conn) error {
	defer c.Close()

	pub, priv, err := box.GenerateKey(rand.Reader)
	if err != nil {
		return fmt.Errorf("could not generate key: %s", err)
	}

	n, err := c.Write(pub[:])
	if err != nil || n != 32 {
		return fmt.Errorf("handshake failed, could not send public key:%s", err)
	}

	var clientPub [32]byte
	if n, err := c.Read(clientPub[:]); n != 32 || err != nil {
		return fmt.Errorf("handshake failed, did not receive public key:%s", err)
	}

	sr := NewSecureReader(c, priv, &clientPub)
	sw := NewSecureWriter(c, priv, &clientPub)

	if _, err := io.Copy(sw, sr); err != nil {
		return fmt.Errorf("serve copy failed: %s", err)
	}

	return nil
}
Beispiel #19
0
func handleConnection(conn net.Conn) {
	connections++
	fmt.Printf("New connection established. Connections number is %d\n", connections)

	number := connections

	defer func() {
		fmt.Printf("Connection #%d closed.\n", number)
		conn.Close()
		connections--
	}()

	for {
		message, err := bufio.NewReader(conn).ReadString('\n') // output message received

		if err != nil {
			if err.Error() != "EOF" {
				fmt.Println("Got bad message: " + string(message))
			}
			break
		}

		if len(message) > 0 {
			conn.Write([]byte("Message Received: " + string(message)))
		}
	}
}
Beispiel #20
0
// hanleTCPConn handle a long live tcp connection.
func handleTCPConn(conn net.Conn, rc chan *bufio.Reader) {
	addr := conn.RemoteAddr().String()
	log.Debug("<%s> handleTcpConn routine start", addr)
	rd := newBufioReader(rc, conn)
	if args, err := parseCmd(rd); err == nil {
		// return buffer bufio.Reader
		putBufioReader(rc, rd)
		switch args[0] {
		case "sub":
			SubscribeTCPHandle(conn, args[1:])
			break
		default:
			conn.Write(ParamReply)
			log.Warn("<%s> unknown cmd \"%s\"", addr, args[0])
			break
		}
	} else {
		// return buffer bufio.Reader
		putBufioReader(rc, rd)
		log.Error("<%s> parseCmd() error(%v)", addr, err)
	}
	// close the connection
	if err := conn.Close(); err != nil {
		log.Error("<%s> conn.Close() error(%v)", addr, err)
	}
	log.Debug("<%s> handleTcpConn routine stop", addr)
	return
}
Beispiel #21
0
func handleClient(conn net.Conn) {
	//	defer conn.Close()
	//	daytime := time.Now().String()
	//	conn.Write([]byte(daytime))
	conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // set 2 minutes timeout
	request := make([]byte, 128)                          // set maxium request length to 128KB to prevent flood attack
	defer conn.Close()                                    // close connection before exit
	for {
		read_len, err := conn.Read(request)
		fmt.Println("read info: ", string(request))
		if err != nil {
			fmt.Println(err)
			break
		}
		fmt.Println(string(request))
		if read_len == 0 {
			break // connection already closed by client
		} else if string(request) == "timestamp" {
			fmt.Println("daytime timestamp")
			daytime := strconv.FormatInt(time.Now().Unix(), 10)
			conn.Write([]byte(daytime))
		} else {
			daytime := time.Now().String()
			conn.Write([]byte(daytime))
		}

		request = make([]byte, 128) // clear last read content
	}
}
Beispiel #22
0
func SetupFTPS(logStruct *FTPLog, connection net.Conn) (bool, error) {
	buffer := make([]byte, 1024)

	connection.Write([]byte("AUTH TLS\r\n"))
	respLen, err := util.ReadUntilRegex(connection, buffer, ftpEndRegex)
	if err != nil {
		return false, err
	}

	logStruct.AuthTLSResp = string(buffer[0:respLen])
	retCode := ftpEndRegex.FindStringSubmatch(logStruct.AuthTLSResp)[1]
	if strings.HasPrefix(retCode, "2") {
		return true, nil
	} else {
		connection.Write([]byte("AUTH SSL\r\n"))
		respLen, err := util.ReadUntilRegex(connection, buffer, ftpEndRegex)
		if err != nil {
			return false, err
		}

		logStruct.AuthSSLResp = string(buffer[0:respLen])
		retCode := ftpEndRegex.FindStringSubmatch(logStruct.AuthSSLResp)[1]

		if strings.HasPrefix(retCode, "2") {
			return true, nil
		}
	}

	return false, nil
}
Beispiel #23
0
//	We receive the chart script from our parent, we have to handle the data and send it to children.
func (s *Server) HandleChartTransfer(socket net.Conn) {
	file, _ := os.Create("./resources/chart.html")

	log.Println("Begginning receiving chart")

	for {
		read := make([]byte, 4096)

		n, _ := socket.Read(read)

		if sip.ExtractType(string(read[:n])) == "END" {
			break
		}

		file.Write(read[:n])

		socket.Write([]byte("INF||"))
	}

	log.Println("Done receiving chart")

	file.Close()

	for i := 0; i < s.ChildNumber; i++ {
		SendChart(s.Children[i])
	}
}
Beispiel #24
0
func (this *Server) receive(buf []byte, conn net.Conn) ([]byte, error) {
	conn.SetDeadline(time.Now().Add(this.connTimeout))
	readNum := 0
	length := len(buf)

	var num int
	var err error
	for readNum < length {
		num, err = conn.Read(buf[readNum:])
		if err != nil {
			if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
				time.Sleep(time.Second)
				continue
			}
			return nil, err
		}
		this.logger.Debug("Read %d bytes: %s", num, string(buf))
		readNum += num
	}

	_, err = conn.Write([]byte("ok"))
	if err != nil {
		return nil, err
	}

	return buf, nil
}
func (self *ProtobufRequestHandler) WriteResponse(conn net.Conn, response *protocol.Response) error {
	data, err := response.Encode()
	if err != nil {
		log.Error("error encoding response: %s", err)
		return err
	}
	if len(data) >= MAX_RESPONSE_SIZE {
		pointCount := len(response.Series.Points)
		firstHalfPoints := response.Series.Points[:pointCount]
		secondHalfPoints := response.Series.Points[pointCount:]
		response.Series.Points = firstHalfPoints
		err := self.WriteResponse(conn, response)
		if err != nil {
			return err
		}
		response.Series.Points = secondHalfPoints
		return self.WriteResponse(conn, response)
	}

	buff := bytes.NewBuffer(make([]byte, 0, len(data)+8))
	binary.Write(buff, binary.LittleEndian, uint32(len(data)))
	_, err = conn.Write(append(buff.Bytes(), data...))
	if err != nil {
		log.Error("error writing response: %s", err)
		return err
	}
	return nil
}
Beispiel #26
0
func handleCient(conn net.Conn) {
	conn.SetDeadline(time.Now().Add(2 * time.Minute))
	request := make([]byte, 128)
	defer conn.Close()

	for {
		read_len, err := conn.Read(request)

		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %s", err)
			break
		}

		fmt.Printf(string(read_len))

		// if read_len == 0 {
		// 	break
		// } else if string(request) == "timestamp" {
		daytime := time.Now().String()
		conn.Write([]byte(daytime))
		// }
	}

	request = make([]byte, 128)
}
Beispiel #27
0
func handShake(conn net.Conn) (err error) {
	const (
		idVer     = 0
		idNmethod = 1
	)
	// version identification and method selection message in theory can have
	// at most 256 methods, plus version and nmethod field in total 258 bytes
	// the current rfc defines only 3 authentication methods (plus 2 reserved),
	// so it won't be such long in practice

	buf := make([]byte, 258)

	var n int
	// make sure we get the nmethod field
	if n, err = io.ReadAtLeast(conn, buf, idNmethod+1); err != nil {
		return
	}
	if buf[idVer] != socksVer5 {
		return errVer
	}
	nmethod := int(buf[idNmethod])
	msgLen := nmethod + 2
	if n == msgLen { // handshake done, common case
		// do nothing, jump directly to send confirmation
	} else if n < msgLen { // has more methods to read, rare case
		if _, err = io.ReadFull(conn, buf[n:msgLen]); err != nil {
			return
		}
	} else { // error, should not get extra data
		return errAuthExtraData
	}
	// send confirmation: version 5, no authentication required
	_, err = conn.Write([]byte{socksVer5, 0})
	return
}
//handle read and write
func handleConnection(conn net.Conn) {

	//handle read
	go func(conn net.Conn) {
		reader := bufio.NewReader(os.Stdin)
		for {
			fmt.Print(">>")
			line, _, _ := reader.ReadLine()
			conn.Write([]byte(line))
		}
	}(conn)
	//handle write
	go func(conn net.Conn) {
		bs := make([]byte, 1024)
		for {
			l, err := conn.Read(bs)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
				conn.Close()
			}
			fmt.Println("<<", string(bs[:l]))
		}
	}(conn)

}
Beispiel #29
0
func httpServer(c net.Conn) {
	buf := make([]byte, 5120)
	nr, _ := c.Read(buf)
	fmt.Println(string(buf[:nr]))
	c.Write([]byte(stdresponse))
	c.Close()
}
Beispiel #30
-1
func receiveConn(conn net.Conn){
	var buffer []byte
	var err error
	var n int

	// if the max length of request is 128k
	// also can use bufio.NewReader().ReadLine()
	buffer = make([]byte,128)
	for {
		n, err = conn.Read(buffer)

		// if client connection closed will happen io eof
		// other reason example network timeout will happen
		// timeout error
		if err != nil {
			if err == io.EOF {
				log.Println("[Request][EOF]:", "client disconnect")
			}
			conn.Close()
			break
		}

		if n != 0 {
			fmt.Println("[Receive]:", string(buffer))
			conn.Write(buffer)
		}else {
			conn.Write([]byte("error request"))
		}

		buffer = make([]byte, 128)    //clear buffer
	}
}