Example #1
0
func readUntilCrLf(con *net.TCPConn) (line []byte, err os.Error) {

	buf := make([]byte, 1)
	var data []byte
	crSeen := false

	for {
		_, err := con.Read(buf)
		if err != nil {
			if err == os.EOF {
				break
			} else {
				return nil, err
			}
		}
		if crSeen {
			if buf[0] == 10 {
				break
			} else {
				crSeen = false
				data = bytes.Add(data, buf)
			}
		} else {
			if buf[0] == 13 {
				crSeen = true
			} else {
				data = bytes.Add(data, buf)
			}
		}
	}

	return data, nil
}
Example #2
0
File: tcp04.go Project: ra/go-samp
// 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
}
Example #3
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
}
Example #4
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
}
Example #5
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
}
Example #6
0
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
		}
	}
}
Example #7
0
func (p *proxy) pipe(src, dst *net.TCPConn, powerCallback common.Callback) {
	//data direction
	islocal := src == p.lconn
	//directional copy (64k buffer)
	buff := make([]byte, 0xffff)
	for {
		n, err := src.Read(buff)
		if err != nil {
			p.err("Read failed '%s'\n", err)
			return
		}
		b := buff[:n]
		//show output
		if islocal {
			b = getModifiedBuffer(b, powerCallback)
			n, err = dst.Write(b)
		} else {
			//write out result
			n, err = dst.Write(b)
		}
		if err != nil {
			p.err("Write failed '%s'\n", err)
			return
		}
	}
}
Example #8
0
func listen(conn *net.TCPConn) {
	resp := make([]byte, 10240)
	for {
		fmt.Printf("Waiting to read\n")
		readLen, err := conn.Read(resp[0:])
		if err != nil {
			fmt.Printf("Something broke\n")
			return
		}
		if readLen == 0 {
			fmt.Printf("Server stopped\n")
			return
		}

		fmt.Printf("Read %d Bytes\n", readLen)
		pduResp := RawPdu(resp)

		switch pduResp.command_id {
		case PDU_COMMAND_SUBMIT_SM + PDU_COMMAND_RESP:
			fmt.Printf("Listener: Submit Message ID: %s\n", string(pduResp.Message_id))
		case PDU_COMMAND_BIND_RX + PDU_COMMAND_RESP, PDU_COMMAND_BIND_TX + PDU_COMMAND_RESP, PDU_COMMAND_BIND_TRX + PDU_COMMAND_RESP:
			fmt.Printf("Listener: BIND Response status: %d\n", pduResp.Command_status)
		case PDU_COMMAND_DELIVER_SM:
			fmt.Printf("Listener: DLR status: %d\n", pduResp.Command_status)
		}
	}
}
Example #9
0
func readServer(pTCPConn *net.TCPConn) {
	buffer := make([]byte, 1024)
	tempBuf := make([]byte, 4)
	for {
		bufferSize, err := pTCPConn.Read(buffer)
		if err != nil {
			return
		}
		if bufferSize >= 4 {
			copy(tempBuf, buffer)
			length := common.BytesToInt(tempBuf)

			//fmt.Println("length:", length)
			newbuffer := make([]byte, length)
			copy(newbuffer, buffer[4:])

			msg := &protocol.WMessage{}
			err = proto.Unmarshal(newbuffer, msg)
			if err != nil {
				fmt.Println("unmarshal:", err)
				return
			}
			fmt.Println("解码:", msg.String())
		}

	}
}
Example #10
0
// Handling a particular TCP connection.
func handleTCPConnection(conn *net.TCPConn, noteChannel chan synth.DelayedNoteData) {
	defer conn.Close()
	buffer := make([]byte, 256)
	for {
		rlen, err := conn.Read(buffer)
		if err == io.EOF {
			return
		} else if err != nil {
			fmt.Println("Failed to read from TCP socket: " + err.Error())
			return
		}

		if rlen > 0 {
			strs := strings.Split(strings.TrimSpace(string(buffer[:rlen])), "\n")
			for _, v := range strs {
				err = HandleMessage(v, noteChannel)
				if err != nil {
					fmt.Println("Failed to handle message \"" + v + "\": " + err.Error())
				}
			}
		}

		buffer = make([]byte, 256)
		time.Sleep(1 * time.Millisecond)
	}
}
Example #11
0
// Reading network message as a byte array,
// where first 4 bytes is a uint length for all message
func ReadMessage(conn *net.TCPConn) (msg []byte, err TreeError) {
	var (
		msg_len_byte = make([]byte, 4)
		msg_len      uint32
		rlen         int
	)
	err.From = FROM_READ_MESSAGE
	rlen, err.Err = conn.Read(msg_len_byte)
	if !err.IsNull() {
		return
	}

	if rlen != 4 {
		err.Err = errors.New("Data lenght reading error. Check API details")
		return
	}

	msg_len = binary.LittleEndian.Uint32(msg_len_byte)
	msg = make([]byte, int(msg_len))
	rlen, err.Err = conn.Read(msg)
	if !err.IsNull() {
		return
	}

	if rlen != int(msg_len) {
		err.Err = errors.New(fmt.Sprintf("Message length not equal to given length. Check API details. Given %d message length, but recieved %d", int(msg_len), rlen))
		return
	}

	return
}
Example #12
0
func (b *Smarthomebox) recv(conn *net.TCPConn) {
	b.Wg.Add(1)
	defer func() {
		b.Wg.Done()
	}()
	for {
		select {
		case <-b.ExitChan:
			return
		default:
		}

		buffer := make([]byte, 1024)
		//length, _ := conn.Read(buffer)
		conn.Read(buffer)
		if buffer[3] == 0x80 && buffer[4] == 0x08 {
			b.setnamefeedback(conn, buffer)
		} else if buffer[3] == 0x80 && buffer[4] == 0x04 {
			b.opfeedback(conn, buffer)
		} else if buffer[3] == 0x80 && buffer[4] == 0x0A {
			b.delfeedback(conn, buffer)
			log.Println("feedback del")
		}

		//	log.Printf("recv %X\n", buffer[0:length])
	}
}
Example #13
0
func benchcore(host, req *string, port int, callback bench_callback) {
	var fail, bs, speed int64

	buf := make([]byte, 1500)
	reqLen := len(*req)
	var conn *net.TCPConn

	ds := fmt.Sprintf("%ds", *sec)

	dur, _ := time.ParseDuration(ds)
	timer := time.NewTimer(dur)

	for {
	nextconn:
		select {
		case <-timer.C:
			callback(fail, bs, speed)
			fmt.Println("Some of our childrens died.")
			return
		default:
			conn = socket.Socket(host, port)
			if conn == nil {
				fail++
				continue
			}
			wlen, err := conn.Write([]byte(*req))
			if wlen != reqLen || err != nil {
				fail++
				conn.Close()
				continue
			}
			if httpVersion == 0 {
				err := conn.CloseWrite()
				if err != nil {
					fail++
					conn.Close()
					continue
				}
			}
			if *force == false {
				for {
					b, err := conn.Read(buf)
					if err == io.EOF {
						break
					} else if err != nil {
						fail++
						conn.Close()
						break nextconn
					}
					bs += int64(b)
				}
			}
			if conn.Close() != nil {
				fail++
				continue
			}
			speed++
		}
	}
}
Example #14
0
// Pipe starts bridging with two tcp connection
func Pipe(dst *net.TCPConn, src *net.TCPConn, f *func([]byte) []byte) error {
	defer src.CloseRead()
	defer dst.CloseWrite()

	rb := make([]byte, 4096)

	for {
		rsize, err := src.Read(rb)
		if err != nil {
			if isRecoverable(err) {
				continue
			}
			return err
		}

		var wb []byte
		if f != nil {
			wb = (*f)(rb[:rsize])
		} else {
			wb = rb[:rsize]
		}
		wWrote := 0
		wTotal := len(wb)
		for wWrote != wTotal {
			wSize, err := dst.Write(wb[wWrote:])
			wWrote += wSize
			if err != nil {
				if isRecoverable(err) {
					continue
				}
				return err
			}
		}
	}
}
Example #15
0
func readloop(conn *net.TCPConn, clist *[]ChanPair, controlc chan chan string) {
	output := make(chan string, 2048)
	input := make(chan string, 2048)
	controlc <- output
	controlc <- input
	address := conn.RemoteAddr()
	player := parsing.NewPlayer(address.String())
	for {
		b := make([]byte, 4096)
		n, err := conn.Read(b[:])
		data := b[:n]
		if err != nil {
			fmt.Println(err)
		}

		select {
		case str := <-input:
			conn.Write([]uint8(str))
		default:
		}

		if len(string(data)) == 0 {
			fmt.Println("PARTING:", address.String())
			conn.Close()
			return
		}
		conn.Write(parsing.Parse(player, string(data), output))
	}
}
Example #16
0
func SockRead(con *net.TCPConn, buf []byte) (n int, e error) {
	n, e = con.Read(buf)
	if e == nil {
		count_rcvd(uint64(n))
	}
	return
}
Example #17
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
		}
	}
}
Example #18
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()
}
Example #19
0
func session(conn *net.TCPConn) {
	fmt.Println("here")
	var buf [2048]byte
	code := 0
	for {
		t := time.Now().Add(time.Millisecond * 100)
		conn.SetReadDeadline(t)
		n, err := conn.Read(buf[:])
		e, ok := err.(net.Error)

		if err != nil && ok && !e.Timeout() {
			fmt.Println(err)
			break
		}

		if n > 0 {
			process(conn, buf[:n])
		} else {
			msg := fmt.Sprintf("%v", code)
			code++
			conn.Write([]byte(msg))
		}
	}
	fmt.Println("session ended")
}
Example #20
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
}
Example #21
0
func (p *Proxy) pipe(src, dst *net.TCPConn) {
	//data direction
	islocal := src == p.lconn

	//directional copy (64k buffer)
	buff := make([]byte, 0xffff)
	for {
		n, err := src.Read(buff)
		if err != nil {
			p.err("Read failed '%s'\n", err)
			return
		}
		b := buff[:n]
		//show output
		n, err = dst.Write(b)
		if err != nil {
			p.err("Write failed '%s'\n", err)
			return
		}
		if islocal {
			p.sentBytes += uint64(n)
		} else {
			p.receivedBytes += uint64(n)
		}
	}
}
Example #22
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())
		}
	}
}
Example #23
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
}
Example #24
0
func readRemoteLoop(client, remote *net.TCPConn, stopChan chan<- bool) {
	defer func() {
		stopChan <- true
	}()
	addr := client.RemoteAddr()

	for {
		var buf [4096]byte
		nr, err := remote.Read(buf[:])
		if err != nil && err != os.EOF {
			log.Printf("%v: Failed to read from the remote: %v", addr, err)
			return
		}

		start := 0
		for start < nr {
			nw, err := client.Write(buf[start:nr])
			if err != nil && err != os.EOF {
				log.Printf("%v: Failed to write to the client: %v", addr, err)
				return
			}
			start += nw
		}
	}
}
Example #25
0
File: gopf.go Project: no2key/gopf
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
		}
	}
}
Example #26
0
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
}
Example #27
0
func client(conn *net.TCPConn) {
	stashBytes := make([]byte, 0)
	buf := make([]byte, 1024)
	var temp []byte
	for {
		count, err := conn.Read(buf)
		if err != nil {
			fmt.Println(err)
			break
		}
		if len(stashBytes) > 0 {
			temp = append(stashBytes, buf[:count]...)
		} else {
			temp = buf[:count]
		}
		start := 0
		for start < count {
			l := int(binary.BigEndian.Uint16(temp[start : start+2]))
			if start+l > count {
				stashBytes = temp[start:]
				break
			}
			eid, recvMsg := ParseProtocal(temp[start+2 : start+l])
			fmt.Println(eid, string(recvMsg))
			start += l
		}
	}
	conn.Close()
}
Example #28
0
File: util.go Project: 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
}
Example #29
0
func Service(conn *net.TCPConn) {
	b := make([]byte, 1024)
	for {
		lenth, _ := conn.Read(b)
		DisCmd(string(b[:lenth]))
	}
}
Example #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]

		}

	}

}