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

news2024/12/23 18:21:47

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 uintptr
	var pukey *uintptr
	if 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 uint32
	if 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 uint32
	if 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 main

import (
	"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) error

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 uint32
	if 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 uint32
	if 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.Overlapped
	WsaBuf     syscall.WSABuf
	NBytes     uint32
	isRead     bool
	cliSock    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.Len
	data.isRead = true
	flag := 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.Overlapped
	var ioSize uint32
	var key uintptr
	for {
		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)
		}
	}
}

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1690347.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

场内期权怎么开户?佣金手续费最低是多少?

今天期权懂带你了解场内期权怎么开户&#xff1f;佣金手续费最低是多少&#xff1f;我国的首个场内期权是50ETF期权&#xff0c;随着投资者对期权产品日渐熟悉&#xff0c;投资者参与数量与交易量稳步增长。 场内期权怎么开户&#xff1f; 满足资金要求&#xff1a;根据监管要…

DLT645-97/07通信规约 | 报文解析 | 组织报文与解析报文(C++)

文章目录 一、DLT645通信规约1.DLT645-1997通信规约2.DLT645-2007通讯规约3.DLT645-1997与DLT645-2007的区别 二、DLT645通信规约报文解析1.DLT645-1997通信规约报文解析2.DLT645-2007通信规约报文解析 三、C代码组织报文与解析报文 一、DLT645通信规约 DLT645协议&#xff0c;…

LeetCode 131题详解:高效分割回文串的递归与动态规划方法

❤️❤️❤️ 欢迎来到我的博客。希望您能在这里找到既有价值又有趣的内容&#xff0c;和我一起探索、学习和成长。欢迎评论区畅所欲言、享受知识的乐趣&#xff01; 推荐&#xff1a;数据分析螺丝钉的首页 格物致知 终身学习 期待您的关注 导航&#xff1a; LeetCode解锁100…

每日一题(1)

在看一本08年出版的书的时候&#xff0c;看到了这样一个问题&#xff0c;感觉答案很奇怪&#xff1a; public class demo_p22 {public static void main(String args[]){int sCook1,sFish2;//各技能标记character ch1new character();if(ch1.haveSkill(sCook))System.out.print…

大数据量上传FTP

背景 笔者有一个需求是把将近一亿条数据上传到FTP服务器中&#xff0c;这些数据目前是存储在mysql中&#xff0c;是通过关联几张表查询出来的&#xff0c;查询出来的数据结果集一共是6个字段。要求传输的时候拆分成一个个小文件&#xff0c;每个文件大小不能超过500M。我的测试…

谷歌蜘蛛池是什么?

或称为谷歌爬虫池&#xff0c;是一项专门针对谷歌搜索引擎优化&#xff08;SEO&#xff09;的先进技术&#xff0c;这种技术的主要目的是通过建立庞大的网站群体和复杂的链接结构来吸引和维持谷歌的爬虫程序的注意力&#xff0c;其核心是通过这种结构优化&#xff0c;增强特定网…

使用B2M 算法批量将可执行文件转为灰度图像

参考论文 基于二进制文件的 C 语言编译器特征提取及识别 本实验使用 B2M 算法将可执行文件转为灰度图像&#xff0c;可执行文件转为灰度图的流程如图 4-3 所示。将 可执行文件每 8 位读取为一个无符号的的整型常量&#xff0c;一个可执行文件得到一个一维向量&#xff0c; …

mac版本Phpstudy本地环境安装Discuz教程【2024】

此方法适用于m1版本的mac版本Phpstudy本地环境安装Discuz&#xff0c;当然同样使用更高版本的mac端。网上各种安装教程参差不齐&#xff0c;根本解决不了小白的入门需求&#xff0c;以下是最新且直接明了的安装教程。 Phpstudy本地环境安装Discuz教程&#xff1a; 1、安装Phps…

1075: 求最小生成树(Prim算法)

解法&#xff1a; 总结起来&#xff0c;Prim算法的核心思想是从一个顶点开始&#xff0c;一步一步地选择与当前最小生成树相邻的且权值最小的边&#xff0c;直到覆盖所有的顶点&#xff0c;形成一个最小生成树。 #include<iostream> #include<vector> using names…

【管理篇 / 升级】❀ 14. FortiOS 7.4固件升级新规后的7.4.4版本的升级 ❀ FortiGate 防火墙

【简介】相信看过上一篇文章的都已经知道了&#xff0c;FortiOS 7.4版本的固件升级和降级都增加了条件&#xff0c;那就是需要设备在服务期内&#xff0c;但是小版本的升级是允许的&#xff0c;例如7.4.0升级到7.4.1、7.4.2&#xff0c;现在最新版本7.4.4来了。 获得FortiOS 7.…

【C++】牛客——OR64 求和

✨题目链接&#xff1a; OR64 求和 ✨题目描述 输入两个整数 n 和 m&#xff0c;从数列1&#xff0c;2&#xff0c;3.......n 中随意取几个数,使其和等于 m ,要求将其中所有的可能组合列出来 ✨输入描述: 每个测试输入包含2个整数,n和m ✨输出描述: 按每个组合的字典序排列…

【系统架构师】-案例篇(十五)SOA、微服务与数据库

1、可复用构件应具备哪些属性 可用性&#xff1a;构件必须易于理解和使用。 质量&#xff1a;构件及其变形必须能正确工作。 适应性&#xff1a;构件应该易于通过参数化等方式在不同语境中进行配置。 可移植性&#xff1a;构件应能在不同的硬件运行平台和软件环境中工作。 可变…

数组-区间合并

一、题目描述 二、题目思路 这里提供满足基本要求的解题思路&#xff1a; 1.先对列表内按照start大小升序排序&#xff0c;这里创建Comparator接口的实现类&#xff0c;重写compare方法。 2.遍历intervals&#xff0c;设置laststart、lastend两个变量与当前区间相比较&#…

LVGL显示中文字体及其它语言文字详细笔记教程

在前面几篇博客文章中&#xff0c;已经对LVGL的移植和使用进行了较为详细的介绍&#xff0c;在本文中将讲解如何在LVGL的控件中显示中文字体及其它语言字体。 LVGL在VScode中安装模拟器运行配置笔记教程_vscode lvgl-CSDN博客 LVGL移植到STM32 MCU平台详细经验笔记教程-CSDN博…

Day36 代码随想录打卡|二叉树篇---翻转二叉树

题目&#xff08;leecode T226&#xff09;&#xff1a; 给你一棵二叉树的根节点 root &#xff0c;翻转这棵二叉树&#xff0c;并返回其根节点。 方法&#xff1a; 迭代法 翻转二叉树&#xff0c;即从根节点开始&#xff0c;一一交换每个节点的左右孩子节点&#xff0c;然后…

【Linux】-Zookeeper安装部署[17]

简介 apache ZooKeeper是一个分布式的&#xff0c;开放源码的分布式应用程序协调服务&#xff0c;是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件&#xff0c;提供的功能包括&#xff1a;配置维护、域名服务、分布式同步、组服务等。 除了为Hadoop和H…

程序员做推广?我劝你别干

关注卢松松&#xff0c;会经常给你分享一些我的经验和观点。 这是卢松松会员专区&#xff0c;一位会员朋友的咨询&#xff0c;如果你也有自研产品&#xff0c;但不知道如何推广&#xff0c;一定要阅读本文!强烈建议收藏关注&#xff0c;因为你关注的人&#xff0c;决定你看到的…

【spring】@ControllerAdvice注解学习

ControllerAdvice介绍 ControllerAdvice 是 Spring 框架提供的一个注解&#xff0c;用于定义一个全局的异常处理类或者说是控制器增强类&#xff08;controller advice class&#xff09;。这个特性特别适用于那些你想应用于整个应用程序中多个控制器的共有行为&#xff0c;比…

VeraCrypt设置步骤操作说明

一、VeraCrypt软件说明 VeraCrypt是一个开源的磁盘加密软件&#xff0c;是TrueCrypt的继承者和改进版。它提供了强大的数据加密功能&#xff0c;可以对整个磁盘、操作系统分区或移动存储设备进行加密。 二、VeraCrypt软件操作步骤 01&#xff09;首先在电脑中创建一个新的空…