Coder Social home page Coder Social logo

tcp的read方法阻塞 about magpie HOT 1 CLOSED

haifenghuang avatar haifenghuang commented on July 29, 2024
tcp的read方法阻塞

from magpie.

Comments (1)

haifenghuang avatar haifenghuang commented on July 29, 2024

tcp的代码在net.go文件中,其中的Read方法如下:

func (t *TcpConnObject) Read(line string, args ...Object) Object {
	if len(args) != 0 {
		panic(NewError(line, ARGUMENTERROR, "0", len(args)))
	}

	bytes, err := ioutil.ReadAll(t.Conn)
	if err != nil {
		return NewNil(err.Error())
	}

	return NewString(string(bytes))
}

这里使用的是ioutil.ReadAll这个方法,它是阻塞的。

你可能是希望如下的代码吧:

func (t *TcpConnObject) Read(line string, args ...Object) Object {
	if len(args) != 1 {
		panic(NewError(line, ARGUMENTERROR, "1", len(args)))
	}

	length, ok := args[0].(*Integer) //The first parameter is the length you want to read
	if !ok {
		panic(NewError(line, PARAMTYPEERROR, "first", "read", "*Integer", args[0].Type()))
	}

	data := make([]byte, length.Int64);

	readTotal := 0
	readBytes := 0
	var err error
	for {
		if readTotal == len(data) {
			break
		}
		if readBytes, err = t.Conn.Read(data[readTotal:]); err != nil {
			break
		}
		readTotal += readBytes
	}

	if err != nil {
		return NewNil(err.Error())
	}

	return NewString(string(data))
}

from magpie.

Related Issues (17)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.