如何在Go编程语言中使用WSASocket函数创建一个套接字?

huangapple go评论87阅读模式
英文:

How to create a socket using WSASocket function in go programming language?

问题

有人知道如何在Go编程语言中创建一个由WSASocket()函数返回的SOCKET吗?

使用普通的syscall.Socket类型syscall.Bind会导致:
WSAENOTSOCK - 错误10038 - 尝试对非套接字进行操作。指定的套接字参数引用的是文件,而不是套接字。

谢谢

英文:

Does anyone know how to create a SOCKET as returned by WSASocket() function in go programming language?

Using a normal syscall.Socket type syscall.Bind results in:
WSAENOTSOCK - Error 10038 - An operation was attempted on something that is not a socket. The specified socket parameter refers to a file, not a socket.

Thanks

答案1

得分: 1

我们不使用这样低级的API,我们使用net.Dial。例如。

func main() {
        var (
                host          = "127.0.0.1"
                port          = "9998"
                remote        = host + ":" + port
                msg    string = "test"
        )

        con, error := net.Dial("tcp4", remote)
        if error != nil {
                fmt.Printf("主机未找到:%s\n", error)
                os.Exit(1)
        } else {
                defer con.Close()
        }

        in, error := con.Write([]byte(msg))
        if error != nil {
                fmt.Printf("发送数据时出错:%s, in:%d\n", error, in)
                os.Exit(2)
        }

        fmt.Println("连接正常")

}

或者,您可以跟踪代码$GOROOT/src/pkg/net/dial.go

英文:

We don't use such low level API, we use net.Dial. ex.

func main() {
        var (
                host          = "127.0.0.1"
                port          = "9998"
                remote        = host + ":" + port
                msg    string = "test"
        )

        con, error := net.Dial("tcp4", remote)
        if error != nil {
                fmt.Printf("Host not found: %s\n", error)
                os.Exit(1)
        } else {
                defer con.Close()
        }

        in, error := con.Write([]byte(msg))
        if error != nil {
                fmt.Printf("Error sending data: %s, in: %d\n", error, in)
                os.Exit(2)
        }

        fmt.Println("Connection OK")

}

Or, you could trace the code $GOROOT/src/pkg/net/dial.go

huangapple
  • 本文由 发表于 2011年11月3日 04:51:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/7987154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定