首页 > 其他分享 >golang io复用端口监听

golang io复用端口监听

时间:2023-07-20 13:45:45浏览次数:29  
标签:err nil 端口 复用 golang unix io 监听

开发高性能server的时候,不可避免的需要接触到io复用——多个线程或者进程,可以创建一个或多个监听程序(监听同一个地址和端口),并且可以多个线程接收数据,让系统进行负载均衡。不同系统下有不同的模型:windows的iocp,linux的epoll和unix的kqueue。这里只讨论linux下的情况。

如果使用io复用,必须要设置监听socket为SO_REUSEADDR和SO_REUSEPORT。设置复用端口和地址还有个好处,就是程序崩溃后,端口监听有可能没有释放,必须要等两分钟才能再次启动程序。如果是端口复用,就是不在乎启动几个进程,所以程序崩溃后可以立马启动新的。

	lc := net.ListenConfig{
		Control: func(network, address string, c syscall.RawConn) error {
			return c.Control(func(fd uintptr) {
                //上面都是默认写法,这里是设置地址复用
				err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
				if err != nil {
					fmt.Println(err)
				}
                //这里是设置端口复用
				err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
				if err != nil {
					fmt.Println(err)
				}
			})
		},
	}
    //udp的例子
	lp, err := lc.ListenPacket(context.Background(), "udp", "0.0.0.0:1234")
	if err != nil {
		fmt.Println(err)
		return
	}
	udpconn := lp.(*net.UDPConn)
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		var data [1024]byte
		for true {
			_, _, err := udpconn.ReadFromUDP(data[:])
			if err != nil {
				fmt.Println(err)
				return
			}
		}
	}()


    //TCP的例子
    l, err := lc.Listen(context.Background(), "tcp", "0.0.0.0:9000")
    if err != nil {
        log.Printf("Could not start TCP listener: %s", err)
        return
    }

    for {
        c, err := l.Accept()
        if err != nil {
        log.Printf("Listener returned: %s", err)
        break
    }

    go func() {
        defer c.Close()
        log.Printf("New connection created")

        _, err := c.Write([]byte("Hello World"))
       if err != nil {
           log.Printf("Unable to write on connection: %s", err)
       }
    }()
}

https://madflojo.medium.com/socket-options-go-multiple-listeners-one-port-7e5257044bb1
https://github.com/libp2p/go-reuseport

标签:err,nil,端口,复用,golang,unix,io,监听
From: https://www.cnblogs.com/studywithallofyou/p/17568073.html

相关文章

  • 洛谷 P9020 - [USACO23JAN] Mana Collection P
    显然,每个法力池最终能收集到的法力只与这个法力池最终被收集到的时间有关。对于一组询问\((s,e)\),假设我们经过了\(k\)个法力池,我们钦定最终被收集到的时间从后到前分别是\(e=a_1,a_2,\cdots,a_k\),那么最大法力值为\(\sum\limits_{i=1}^kc_{a_i}·\sum\limits_{j=2}^i(s-dis......
  • maven-resources-production:igowin-core: java.lang.OutOfMemoryError: Java hea
    MavenResourcesProduction:OutofMemoryErrorinJavaIntroductionInJava,theOutOfMemoryErrorisacommonexceptionthatoccurswhentheJavaVirtualMachine(JVM)cannotallocateenoughmemorytoperformanoperation.Thiserrorisoftenencountered......
  • maven 中的Java version 怎么配置
    配置Maven中的JavaVersion在使用Maven构建项目时,我们常常需要配置Java的版本,以确保项目能够在特定的Java环境中正确运行。本文将介绍如何配置Maven中的Java版本,并提供一个示例来解决一个实际问题。Maven的Java版本配置Maven使用maven-compiler-plugin插件来......
  • Unity UGUI的AspectRatioFitter(宽高比适应器)组件的介绍及使用
    UnityUGUI的AspectRatioFitter(宽高比适应器)组件的介绍及使用1.什么是AspectRatioFitter组件?AspectRatioFitter(宽高比适应器)是UnityUGUI中的一个组件,用于控制UI元素的宽高比例,使其能够根据父容器的大小进行自适应调整。2.为什么要使用AspectRatioFitter组件?AspectRatioFitte......
  • Test Commands-Functions下——创建自定义Test Case
    TestCommands-Functions下_哔哩哔哩_bilibili基于上一节所创建的测试实例,编写多个不同车速的TestCase,若仅改变信号EngineSpeed的值,也要重复编写多次,花费时间长且易出错,这时可通过Functions功能自定义一个TestCase模板,并基于该模板添加多个TestCase用例1)选择Functions——Tes......
  • Visual Studio IDE 2022 - how to disable navigation to decompiled sources
    VisualStudioIDE2022-howtodisablenavigationtodecompiledsources ......
  • Test Commands-Functions上
    TestCommands-Functions上_哔哩哔哩_bilibili1.对于冗长的测试用例,随着添加的内容越多,同时伴随人员编写时间的增加,后续修改测试用例内容,排查错误的难度也随之上升,这时可以使用vTESTstudio自带的工具"Functions"对测试用例进行优化。2.Functions栏在TestTableEditor左下角;用......
  • Perkins Engines: Reliable Power in Harsh Environments and High-Strength Operatio
    PerkinsEngines:ReliablePowerinHarshEnvironmentsandHigh-StrengthOperationsHelloeveryone!TodayIwouldliketosharewithyouapowerfulenginedesignedtocopewithharshenvironmentsandhigh-intensityworkingconditions-thePerkinsengine.W......
  • asp.net Core Actions
    Action方法是在Controllers中定义公共方法使用路由规则将客户端的请求和action方法做映射ActionpublicIActionResultNameOfAction(){ returnView();}这个方法返回一个IActionResult并且方法名称为NameOfAction,action方法返回类型可以是像C#函数中的任意类型,IActionR......
  • SAP HANA 2 SPS07 Revision 071.00
     SymptomThisistheReleaseNotefor SAPHANA2SPS07Revision071.00(2.00.071.00).Itisreleasedforcustomerssince30thofJune,2023.Forfurtherinformationonthe ReleaseStrategy, DownloadingMedia, Installation/Upgrade, SupportedPlatforms ......