Go语言直接使用Windows的IOCP API写一个echo服务器

2024-05-25 03:12

本文主要是介绍Go语言直接使用Windows的IOCP API写一个echo服务器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Go的标准库中Windows下的网络是使用了IOCP的,参见go源码go/src/runtime/netpoll_windows.go,标准库为了与Epoll、kqueue等不同平台的IO模式使用统一的API,进行了封装。

如果想直接使用Windows的IOCP API编程,比如想按照:Windows下的高效网络模型IOCP完整示例中的流程写,就需要自行封装IOCP相关的API,虽然标准库中封装了很多系统调用,但是不是很全,而且API的函数签名也有一些问题,比如:

// Deprecated: CreateIoCompletionPort has the wrong function signature. Use x/sys/windows.CreateIoCompletionPort.
func CreateIoCompletionPort(filehandle Handle, cphandle Handle, key uint32, threadcnt uint32) (Handle, error) {return createIoCompletionPort(filehandle, cphandle, uintptr(key), threadcnt)
}// Deprecated: GetQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.GetQueuedCompletionStatus.
func GetQueuedCompletionStatus(cphandle Handle, qty *uint32, key *uint32, overlapped **Overlapped, timeout uint32) error {var ukey uintptrvar pukey *uintptrif key != nil {ukey = uintptr(*key)pukey = &ukey}err := getQueuedCompletionStatus(cphandle, qty, pukey, overlapped, timeout)if key != nil {*key = uint32(ukey)if uintptr(*key) != ukey && err == nil {err = errorspkg.New("GetQueuedCompletionStatus returned key overflow")}}return err
}// Deprecated: PostQueuedCompletionStatus has the wrong function signature. Use x/sys/windows.PostQueuedCompletionStatus.
func PostQueuedCompletionStatus(cphandle Handle, qty uint32, key uint32, overlapped *Overlapped) error {return postQueuedCompletionStatus(cphandle, qty, uintptr(key), overlapped)
}

看了一下,其实内部调用的函数签名是没问题的,可以使用Go的魔法指令go:linkname来解决:

//go:linkname CreateIoCompletionPort syscall.createIoCompletionPort
func CreateIoCompletionPort(fileHandle syscall.Handle, cpHandle syscall.Handle, key uintptr, threadCnt uint32) (handle syscall.Handle, err error)//go:linkname GetQueuedCompletionStatus syscall.getQueuedCompletionStatus
func GetQueuedCompletionStatus(cpHandle syscall.Handle, qty *uint32, key *uintptr, overlapped **syscall.Overlapped, timeout uint32) (err error)//go:linkname PostQueuedCompletionStatus syscall.postQueuedCompletionStatus
func PostQueuedCompletionStatus(cphandle syscall.Handle, qty uint32, key uintptr, overlapped *syscall.Overlapped) (err error)

另外还需要使用到一些API,比如WSACreateEventWSAWaitForMultipleEventsWSAResetEventWSAGetOverlappedResult,就需要自行从Ws2_32.dll中装载了:

var (modws2_32 = syscall.NewLazyDLL("Ws2_32.dll")procWSACreateEvent           = modws2_32.NewProc("WSACreateEvent")procWSAWaitForMultipleEvents = modws2_32.NewProc("WSAWaitForMultipleEvents")procWSAResetEvent            = modws2_32.NewProc("WSAResetEvent")procWSAGetOverlappedResult   = modws2_32.NewProc("WSAGetOverlappedResult")
)func WSACreateEvent() (Handle syscall.Handle, err error) {r1, _, e1 := syscall.SyscallN(procWSACreateEvent.Addr())if r1 == 0 {err = errnoErr(e1)}return syscall.Handle(r1), nil
}func WSAWaitForMultipleEvents(cEvents uint32, lpEvent *syscall.Handle, fWaitAll bool, dwTimeout uint32, fAlertable bool) (uint32, error) {var WaitAll, Alertable uint32if fWaitAll {WaitAll = 1}if fAlertable {Alertable = 1}r1, _, e1 := syscall.SyscallN(procWSAWaitForMultipleEvents.Addr(), uintptr(cEvents), uintptr(unsafe.Pointer(lpEvent)), uintptr(WaitAll), uintptr(dwTimeout), uintptr(Alertable))if r1 == syscall.WAIT_FAILED {return 0, errnoErr(e1)}return uint32(r1), nil
}func WSAResetEvent(handle syscall.Handle) (err error) {r1, _, e1 := syscall.SyscallN(procWSAResetEvent.Addr(), uintptr(handle))if r1 == 0 {err = errnoErr(e1)}return
}func WSAGetOverlappedResult(socket syscall.Handle, overlapped *syscall.Overlapped, transferBytes *uint32, bWait bool, flag *uint32) (err error) {var wait uint32if bWait {wait = 1}r1, _, e1 := syscall.SyscallN(procWSAGetOverlappedResult.Addr(), uintptr(socket), uintptr(unsafe.Pointer(overlapped)),uintptr(unsafe.Pointer(transferBytes)), uintptr(wait), uintptr(unsafe.Pointer(flag)))if r1 == 0 {err = errnoErr(e1)}return
}

笔者尝试了下,完全可以,

在这里插入图片描述

直接附上源码:

package mainimport ("errors""fmt""os""runtime""syscall""unsafe"_ "unsafe"
)//go:linkname CreateIoCompletionPort syscall.createIoCompletionPort
func CreateIoCompletionPort(fileHandle syscall.Handle, cpHandle syscall.Handle, key uintptr, threadCnt uint32) (handle syscall.Handle, err error)//go:linkname GetQueuedCompletionStatus syscall.getQueuedCompletionStatus
func GetQueuedCompletionStatus(cpHandle syscall.Handle, qty *uint32, key *uintptr, overlapped **syscall.Overlapped, timeout uint32) (err error)//go:linkname PostQueuedCompletionStatus syscall.postQueuedCompletionStatus
func PostQueuedCompletionStatus(cphandle syscall.Handle, qty uint32, key uintptr, overlapped *syscall.Overlapped) (err error)//go:linkname errnoErr syscall.errnoErr
func errnoErr(e syscall.Errno) errorvar (modws2_32 = syscall.NewLazyDLL("Ws2_32.dll")procWSACreateEvent           = modws2_32.NewProc("WSACreateEvent")procWSAWaitForMultipleEvents = modws2_32.NewProc("WSAWaitForMultipleEvents")procWSAResetEvent            = modws2_32.NewProc("WSAResetEvent")procWSAGetOverlappedResult   = modws2_32.NewProc("WSAGetOverlappedResult")
)func WSACreateEvent() (Handle syscall.Handle, err error) {r1, _, e1 := syscall.SyscallN(procWSACreateEvent.Addr())if r1 == 0 {err = errnoErr(e1)}return syscall.Handle(r1), nil
}func WSAWaitForMultipleEvents(cEvents uint32, lpEvent *syscall.Handle, fWaitAll bool, dwTimeout uint32, fAlertable bool) (uint32, error) {var WaitAll, Alertable uint32if fWaitAll {WaitAll = 1}if fAlertable {Alertable = 1}r1, _, e1 := syscall.SyscallN(procWSAWaitForMultipleEvents.Addr(), uintptr(cEvents), uintptr(unsafe.Pointer(lpEvent)), uintptr(WaitAll), uintptr(dwTimeout), uintptr(Alertable))if r1 == syscall.WAIT_FAILED {return 0, errnoErr(e1)}return uint32(r1), nil
}func WSAResetEvent(handle syscall.Handle) (err error) {r1, _, e1 := syscall.SyscallN(procWSAResetEvent.Addr(), uintptr(handle))if r1 == 0 {err = errnoErr(e1)}return
}func WSAGetOverlappedResult(socket syscall.Handle, overlapped *syscall.Overlapped, transferBytes *uint32, bWait bool, flag *uint32) (err error) {var wait uint32if bWait {wait = 1}r1, _, e1 := syscall.SyscallN(procWSAGetOverlappedResult.Addr(), uintptr(socket), uintptr(unsafe.Pointer(overlapped)),uintptr(unsafe.Pointer(transferBytes)), uintptr(wait), uintptr(unsafe.Pointer(flag)))if r1 == 0 {err = errnoErr(e1)}return
}type IOData struct {Overlapped syscall.OverlappedWsaBuf     syscall.WSABufNBytes     uint32isRead     boolcliSock    syscall.Handle
}func main() {listenFd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)if err != nil {return}defer func() {syscall.Closesocket(listenFd)syscall.WSACleanup()}()v4 := &syscall.SockaddrInet4{Port: 6000,Addr: [4]byte{},}err = syscall.Bind(listenFd, v4)if err != nil {return}err = syscall.Listen(listenFd, 0)if err != nil {return}hIOCP, err := CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0)if err != nil {return}count := runtime.NumCPU()for i := 0; i < count; i++ {go workThread(hIOCP)}defer PostQueuedCompletionStatus(hIOCP, 0, 0, nil)for {acceptFd, er := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, syscall.IPPROTO_TCP)if er != nil {return}b := make([]byte, 1024)recvD := uint32(0)data := &IOData{Overlapped: syscall.Overlapped{},WsaBuf: syscall.WSABuf{Len: 1024,Buf: &b[0],},NBytes:  1024,isRead:  true,cliSock: acceptFd,}data.Overlapped.HEvent, er = WSACreateEvent()if er != nil {return}size := uint32(unsafe.Sizeof(&syscall.SockaddrInet4{}) + 16)er = syscall.AcceptEx(listenFd, acceptFd, data.WsaBuf.Buf, data.WsaBuf.Len-size*2, size, size, &recvD, &data.Overlapped)if er != nil && !errors.Is(er, syscall.ERROR_IO_PENDING) {er = os.NewSyscallError("AcceptEx", er)continue}_, er = WSAWaitForMultipleEvents(1, &data.Overlapped.HEvent, true, syscall.INFINITE, true)if er != nil {return}WSAResetEvent(data.Overlapped.HEvent)dwBytes := uint32(0)flag := uint32(0)WSAGetOverlappedResult(acceptFd, (*syscall.Overlapped)(unsafe.Pointer(&data)), &dwBytes, true, &flag)if dwBytes == 0 {continue}fmt.Printf("client %d connected\n", acceptFd)_, err = CreateIoCompletionPort(acceptFd, hIOCP, 0, 0)if err != nil {continue}postWrite(data)}
}func postWrite(data *IOData) (err error) {data.isRead = false// 这里输出一下data指针,让运行时不把data给GC掉,否则就会出问题fmt.Printf("%p cli:%d send %s\n", data, data.cliSock, unsafe.String(data.WsaBuf.Buf, data.WsaBuf.Len))err = syscall.WSASend(data.cliSock, &data.WsaBuf, 1, &data.NBytes, 0, &data.Overlapped, nil)if err != nil {fmt.Printf("cli:%d send failed: %s\n", data.cliSock, err)return err}return
}func postRead(data *IOData) (err error) {data.NBytes = data.WsaBuf.Lendata.isRead = trueflag := uint32(0)err = syscall.WSARecv(data.cliSock, &data.WsaBuf, 1, &data.NBytes, &flag, &data.Overlapped, nil)if err != nil && !errors.Is(err, syscall.ERROR_IO_PENDING) {fmt.Printf("cli:%d receive failed: %s\n", data.cliSock, err)return err}return
}func workThread(hIOCP syscall.Handle) {var pOverlapped *syscall.Overlappedvar ioSize uint32var key uintptrfor {err := GetQueuedCompletionStatus(hIOCP, &ioSize, &key, &pOverlapped, syscall.INFINITE)if err != nil {fmt.Printf("GetQueuedCompletionStatus failed: %s\n", err)return}if ioSize == 0 {break}ioData := (*IOData)(unsafe.Pointer(pOverlapped))if ioData.isRead {postWrite(ioData)} else {postRead(ioData)}}
}

源码只是一个示例,有资源泄漏的问题待处理。

这篇关于Go语言直接使用Windows的IOCP API写一个echo服务器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1000321

相关文章

python管理工具之conda安装部署及使用详解

《python管理工具之conda安装部署及使用详解》这篇文章详细介绍了如何安装和使用conda来管理Python环境,它涵盖了从安装部署、镜像源配置到具体的conda使用方法,包括创建、激活、安装包... 目录pytpshheraerUhon管理工具:conda部署+使用一、安装部署1、 下载2、 安装3

Mysql虚拟列的使用场景

《Mysql虚拟列的使用场景》MySQL虚拟列是一种在查询时动态生成的特殊列,它不占用存储空间,可以提高查询效率和数据处理便利性,本文给大家介绍Mysql虚拟列的相关知识,感兴趣的朋友一起看看吧... 目录1. 介绍mysql虚拟列1.1 定义和作用1.2 虚拟列与普通列的区别2. MySQL虚拟列的类型2

Window Server创建2台服务器的故障转移群集的图文教程

《WindowServer创建2台服务器的故障转移群集的图文教程》本文主要介绍了在WindowsServer系统上创建一个包含两台成员服务器的故障转移群集,文中通过图文示例介绍的非常详细,对大家的... 目录一、 准备条件二、在ServerB安装故障转移群集三、在ServerC安装故障转移群集,操作与Ser

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

关于@MapperScan和@ComponentScan的使用问题

《关于@MapperScan和@ComponentScan的使用问题》文章介绍了在使用`@MapperScan`和`@ComponentScan`时可能会遇到的包扫描冲突问题,并提供了解决方法,同时,... 目录@MapperScan和@ComponentScan的使用问题报错如下原因解决办法课外拓展总结@

mysql数据库分区的使用

《mysql数据库分区的使用》MySQL分区技术通过将大表分割成多个较小片段,提高查询性能、管理效率和数据存储效率,本文就来介绍一下mysql数据库分区的使用,感兴趣的可以了解一下... 目录【一】分区的基本概念【1】物理存储与逻辑分割【2】查询性能提升【3】数据管理与维护【4】扩展性与并行处理【二】分区的

使用Python实现在Word中添加或删除超链接

《使用Python实现在Word中添加或删除超链接》在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能,本文将为大家介绍一下Python如何实现在Word中添加或... 在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能。通过添加超

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

NFS实现多服务器文件的共享的方法步骤

《NFS实现多服务器文件的共享的方法步骤》NFS允许网络中的计算机之间共享资源,客户端可以透明地读写远端NFS服务器上的文件,本文就来介绍一下NFS实现多服务器文件的共享的方法步骤,感兴趣的可以了解一... 目录一、简介二、部署1、准备1、服务端和客户端:安装nfs-utils2、服务端:创建共享目录3、服