地址系列规范 Unix domain sockets unix域套接字 AddressFamily Socket 编程

实践:

1、同台主机python程序在收到浏览器端的画图请求后给画图的golang程序发送消息

#coding=utf-8
import socket
import datetime,time
import os

unix_domain_socket = "/tmp/uds_python_golang_v1"
class SocketClient:
    def __init__(self):
        pass

    def connect_to_server(self):

        # unix domain sockets 连接写法
        server_address =unix_domain_socket
        socket_family = socket.AF_UNIX
        socket_type = socket.SOCK_DGRAM

        sock = socket.socket(socket_family, socket_type)
        sock.connect(server_address)
        s="hello server"+datetime.datetime.now().__str__()+os.getcwd()
        sock.sendall(s.encode())
        print(s)
        # data = sock.recv(2)
        # print(f"recv data from server '{server_address}': {data.decode()}")
        sock.close()

if __name__ == "__main__":
  # 调试
    while True:
        time.sleep(2)
        try:
            socket_client_obj = SocketClient()
            socket_client_obj.connect_to_server()
        except Exception as e:
            print(e)
 
const unix_domain_socket = "/tmp/uds_python_golang_v1"
 
                err := os.RemoveAll(unix_domain_socket)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                laddr, err := net.ResolveUnixAddr("unixgram", unix_domain_socket)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                conn, err := net.ListenUnixgram("unixgram", laddr)
                if err != nil {
                    fmt.Println("conn ", err)
                    return

                }
                for {
                    var buf = make([]byte, 1024)
                    _, raddr, err := conn.ReadFromUnix(buf)
                    if err != nil {
                        fmt.Println("ReadFromUnix ", err)
                        continue
                    }
                    recv := string(buf)
                    fmt.Println(recv)
                    _, err = conn.WriteToUnix([]byte("to client: "+recv+fmt.Sprintln(time.Now())), raddr)
                    fmt.Println(raddr)
                    if err != nil {
                        fmt.Println("WriteToUnix ", err)
                        // continue
                    }
 
               
 
 

Go:Unix域套接字 - 知乎 https://zhuanlan.zhihu.com/p/423856852

unix domain socket in Go 详解+示例大集合 https://mp.weixin.qq.com/s/9Mwenob08Zx9zlxyd3eElQ

 

 nl /usr/src/kernels/3.10.0-1160.95.1.el7.x86_64/include/linux/socket.h

 

   114  /* Supported address families. */

   115  #define AF_UNSPEC       0

   116  #define AF_UNIX         1       /* Unix domain sockets          */

   117  #define AF_LOCAL        1       /* POSIX name for AF_UNIX       */

   118  #define AF_INET         2       /* Internet IP Protocol         */

   119  #define AF_AX25         3       /* Amateur Radio AX.25          */

   120  #define AF_IPX          4       /* Novell IPX                   */

   121  #define AF_APPLETALK    5       /* AppleTalk DDP                */

   122  #define AF_NETROM       6       /* Amateur Radio NET/ROM        */

   123  #define AF_BRIDGE       7       /* Multiprotocol bridge         */

   124  #define AF_ATMPVC       8       /* ATM PVCs                     */

   125  #define AF_X25          9       /* Reserved for X.25 project    */

   126  #define AF_INET6        10      /* IP version 6                 */

   127  #define AF_ROSE         11      /* Amateur Radio X.25 PLP       */

   128  #define AF_DECnet       12      /* Reserved for DECnet project  */

   129  #define AF_NETBEUI      13      /* Reserved for 802.2LLC project*/

   130  #define AF_SECURITY     14      /* Security callback pseudo AF */

   131  #define AF_KEY          15      /* PF_KEY key management API */

   132  #define AF_NETLINK      16

   133  #define AF_ROUTE        AF_NETLINK /* Alias to emulate 4.4BSD */

   134  #define AF_PACKET       17      /* Packet family                */

   135  #define AF_ASH          18      /* Ash                          */

   136  #define AF_ECONET       19      /* Acorn Econet                 */

   137  #define AF_ATMSVC       20      /* ATM SVCs                     */

   138  #define AF_RDS          21      /* RDS sockets                  */

   139  #define AF_SNA          22      /* Linux SNA Project (nutters!) */

   140  #define AF_IRDA         23      /* IRDA sockets                 */

   141  #define AF_PPPOX        24      /* PPPoX sockets                */

   142  #define AF_WANPIPE      25      /* Wanpipe API Sockets */

   143  #define AF_LLC          26      /* Linux LLC                    */

   144  #define AF_IB           27      /* Native InfiniBand address    */

   145  #define AF_CAN          29      /* Controller Area Network      */

   146  #define AF_TIPC         30      /* TIPC sockets                 */

   147  #define AF_BLUETOOTH    31      /* Bluetooth sockets            */

   148  #define AF_IUCV         32      /* IUCV sockets                 */

   149  #define AF_RXRPC        33      /* RxRPC sockets                */

   150  #define AF_ISDN         34      /* mISDN sockets                */

   151  #define AF_PHONET       35      /* Phonet sockets               */

   152  #define AF_IEEE802154   36      /* IEEE802154 sockets           */

   153  #define AF_CAIF         37      /* CAIF sockets                 */

   154  #define AF_ALG          38      /* Algorithm sockets            */

   155  #define AF_NFC          39      /* NFC sockets                  */

   156  #define AF_VSOCK        40      /* vSockets                     */

   157  #define AF_MAX          41      /* For now.. */

 

 

 

socket function (winsock2.h) - Win32 apps | Microsoft Learn https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket

The table below lists common values for address family although many other values are possible.

 
 
AfMeaning
AF_UNSPEC
0
The address family is unspecified.
AF_INET
2
The Internet Protocol version 4 (IPv4) address family.
AF_IPX
6
The IPX/SPX address family. This address family is only supported if the NWLink IPX/SPX NetBIOS Compatible Transport protocol is installed.

This address family is not supported on Windows Vista and later.

AF_APPLETALK
16
The AppleTalk address family. This address family is only supported if the AppleTalk protocol is installed.

This address family is not supported on Windows Vista and later.

AF_NETBIOS
17
The NetBIOS address family. This address family is only supported if the Windows Sockets provider for NetBIOS is installed.

The Windows Sockets provider for NetBIOS is supported on 32-bit versions of Windows. This provider is installed by default on 32-bit versions of Windows.

The Windows Sockets provider for NetBIOS is not supported on 64-bit versions of windows including Windows 7, Windows Server 2008, Windows Vista, Windows Server 2003, or Windows XP.

The Windows Sockets provider for NetBIOS only supports sockets where the type parameter is set to SOCK_DGRAM.

The Windows Sockets provider for NetBIOS is not directly related to the NetBIOS programming interface. The NetBIOS programming interface is not supported on Windows Vista, Windows Server 2008, and later.

AF_INET6
23
The Internet Protocol version 6 (IPv6) address family.
AF_IRDA
26
The Infrared Data Association (IrDA) address family.

This address family is only supported if the computer has an infrared port and driver installed.

AF_BTH
32
The Bluetooth address family.

This address family is supported on Windows XP with SP2 or later if the computer has a Bluetooth adapter and driver installed.

 

The type specification for the new socket.

Possible values for the socket type are defined in the Winsock2.h header file.

The following table lists the possible values for the type parameter supported for Windows Sockets 2:

TypeMeaning
SOCK_STREAM
1
A socket type that provides sequenced, reliable, two-way, connection-based byte streams with an OOB data transmission mechanism. This socket type uses the Transmission Control Protocol (TCP) for the Internet address family (AF_INET or AF_INET6).
SOCK_DGRAM
2
A socket type that supports datagrams, which are connectionless, unreliable buffers of a fixed (typically small) maximum length. This socket type uses the User Datagram Protocol (UDP) for the Internet address family (AF_INET or AF_INET6).
SOCK_RAW
3
A socket type that provides a raw socket that allows an application to manipulate the next upper-layer protocol header. To manipulate the IPv4 header, the IP_HDRINCL socket option must be set on the socket. To manipulate the IPv6 header, the IPV6_HDRINCL socket option must be set on the socket.
SOCK_RDM
4
A socket type that provides a reliable message datagram. An example of this type is the Pragmatic General Multicast (PGM) multicast protocol implementation in Windows, often referred to as reliable multicast programming.

This type value is only supported if the Reliable Multicast Protocol is installed.

SOCK_SEQPACKET
5
A socket type that provides a pseudo-stream packet based on datagrams.

 

In Windows Sockets 1.1, the only possible socket types are SOCK_DGRAM and SOCK_STREAM.

 

The table below lists common values for the protocol although many other values are possible.

 
protocolMeaning
IPPROTO_ICMP
1
The Internet Control Message Protocol (ICMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6 and the type parameter is SOCK_RAW or unspecified.

This protocol value is supported on Windows XP and later.

IPPROTO_IGMP
2
The Internet Group Management Protocol (IGMP). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6 and the type parameter is SOCK_RAW or unspecified.

This protocol value is supported on Windows XP and later.

BTHPROTO_RFCOMM
3
The Bluetooth Radio Frequency Communications (Bluetooth RFCOMM) protocol. This is a possible value when the af parameter is AF_BTH and the type parameter is SOCK_STREAM.

This protocol value is supported on Windows XP with SP2 or later.

IPPROTO_TCP
6
The Transmission Control Protocol (TCP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type parameter is SOCK_STREAM.
IPPROTO_UDP
17
The User Datagram Protocol (UDP). This is a possible value when the af parameter is AF_INET or AF_INET6 and the type parameter is SOCK_DGRAM.
IPPROTO_ICMPV6
58
The Internet Control Message Protocol Version 6 (ICMPv6). This is a possible value when the af parameter is AF_UNSPEC, AF_INET, or AF_INET6 and the type parameter is SOCK_RAW or unspecified.

This protocol value is supported on Windows XP and later.

IPPROTO_RM
113
The PGM protocol for reliable multicast. This is a possible value when the af parameter is AF_INET and the type parameter is SOCK_RDM. On the Windows SDK released for Windows Vista and later, this protocol is also called IPPROTO_PGM.

This protocol value is only supported if the Reliable Multicast Protocol is installed.

 

地址系列规范。 地址系列的可能值在 Winsock2.h 头文件中定义。

在针对 Windows Vista 及更高版本发布的 Windows SDK 上,头文件的组织方式已更改,地址系列的可能值在 Ws2def.h 头文件中定义。 请注意, Ws2def.h 头文件会自动包含在 Winsock2.h 中,永远不应直接使用。

当前支持的值是 AF_INET 或 AF_INET6,它们是 IPv4 和 IPv6 的 Internet 地址系列格式。 用于 NetBIOS 的地址系列 (AF_NETBIOS 的其他选项,例如,如果安装了地址系列的 Windows 套接字服务提供商,则支持) 。 请注意,AF_地址系列和PF_协议系列常量的值 (相同,例如 ,AF_INET 和 PF_INET) ,因此可以使用任一常量。

下表列出了地址系列的常见值,尽管许多其他值是可能的。

Af含义
AF_UNSPEC
0
地址系列未指定。
AF_INET
2
Internet 协议版本 4 (IPv4) 地址系列。
AF_IPX
6
IPX/SPX 地址系列。 仅当安装了 NWLink IPX/SPX NetBIOS 兼容传输协议时,才支持此地址系列。

Windows Vista 及更高版本不支持此地址系列。

AF_APPLETALK
16
AppleTalk 地址系列。 仅当安装了 AppleTalk 协议时,才支持此地址系列。

Windows Vista 及更高版本不支持此地址系列。

AF_NETBIOS
17
NetBIOS 地址系列。 仅当安装了适用于 NetBIOS 的 Windows 套接字提供程序时,才支持此地址系列。

32 位版本的 Windows 支持 NetBIOS 的 Windows 套接字提供程序。 默认情况下,此提供程序安装在 32 位版本的 Windows 上。

64 位版本的 Windows 不支持 NetBIOS 的 Windows 套接字提供程序,包括 Windows 7、Windows Server 2008、Windows Vista、Windows Server 2003 或 Windows XP。

适用于 NetBIOS 的 Windows 套接字提供程序仅支持 类型 参数设置为 SOCK_DGRAM的套接字。

适用于 NetBIOS 的 Windows 套接字提供程序与 NetBIOS 编程接口不直接相关。 Windows Vista、Windows Server 2008 及更高版本不支持 NetBIOS 编程接口。

AF_INET6
23
Internet 协议版本 6 (IPv6) 地址系列。
AF_IRDA
26
IrDA (IrDA) 地址系列。

仅当计算机安装了红外端口和驱动程序时,才支持此地址系列。

AF_BTH
32
蓝牙地址系列。

如果计算机安装了蓝牙适配器和驱动程序,则 SP2 或更高版本的 Windows XP 支持此地址系列。

[in] type

新套接字的类型规范。

套接字类型的可能值在 Winsock2.h 头文件中定义。

下表列出了 Windows 套接字 2 支持 的类型 参数的可能值:

类型含义
SOCK_STREAM
1
一种套接字类型,它通过 OOB 数据传输机制提供排序的、可靠的双向、基于连接的字节流。 此套接字类型对 Internet 地址系列 (AF_INET 或AF_INET6) 使用传输控制协议 (TCP) 。
SOCK_DGRAM
2
支持数据报的套接字类型,这些数据报是固定 (通常较小) 最大长度的无连接、不可靠的缓冲区。 此套接字类型对 Internet 地址系列 (AF_INET 或AF_INET6) 使用用户数据报协议 (UDP) 。
SOCK_RAW
3
一种套接字类型,它提供允许应用程序操作下一层协议标头的原始套接字。 若要操作 IPv4 标头,必须在套接字上设置 IP_HDRINCL 套接字选项。 若要操作 IPv6 标头,必须在套接字上设置 IPV6_HDRINCL 套接字选项。
SOCK_RDM
4
提供可靠消息数据报的套接字类型。 此类型的一个示例是 Windows 中的实用常规多播 (PGM) 多播协议实现,通常称为 可靠多播编程

仅当安装了可靠多播协议时,才支持此 类型 值。

SOCK_SEQPACKET
5
提供基于数据报的伪流数据包的套接字类型。

 

在 Windows 套接字 2 中,引入了新的套接字类型。 应用程序可以通过 WSAEnumProtocols 函数动态发现每个可用传输协议的属性。 因此,应用程序可以确定地址系列的可能的套接字类型和协议选项,并在指定此参数时使用此信息。 Winsock2.h 和 Ws2def.h 头文件中的套接字类型定义将随着新的套接字类型、地址系列和协议的定义而定期更新。

在 Windows 套接字 1.1 中,唯一可能的套接字类型是 SOCK_DGRAM 和 SOCK_STREAM。

[in] protocol

要使用的协议。 协议参数的可能选项特定于指定的地址系列和套接字类型。 协议的可能值在 Winsock2.h 和 Wsrm.h 头文件中定义。

在针对 Windows Vista 及更高版本发布的 Windows SDK 上,头文件的组织已更改,此参数可以是 Ws2def.h 头文件中定义的 IPPROTO 枚举类型的值之一。 请注意, Ws2def.h 头文件会自动包含在 Winsock2.h 中,永远不应直接使用。

如果指定值 0,则调用方不希望指定协议,服务提供商将选择要使用的 协议 。

当 af 参数AF_INET或AF_INET6且类型为SOCK_RAW时,为协议指定的值在 IPv6 或 IPv4 数据包标头的协议字段中设置。

下表列出了 协议 的常见值,尽管许多其他值是可能的。

协议含义
IPPROTO_ICMP
1
Internet 控制消息协议 (ICMP) 。 当 af 参数 AF_UNSPEC、 AF_INET或 AF_INET6 且 类型 参数 SOCK_RAW 或未指定时,此值可能为 。

Windows XP 及更高版本支持此 协议 值。

IPPROTO_IGMP
2
Internet 组管理协议 (IGMP) 。 当 af 参数 AF_UNSPEC、 AF_INET或 AF_INET6 且 类型 参数 SOCK_RAW 或未指定时,此值可能为 。

Windows XP 及更高版本支持此 协议 值。

BTHPROTO_RFCOMM
3
蓝牙射频通信 (蓝牙 RFCOMM) 协议。 当 af 参数AF_BTH且类型参数SOCK_STREAM时,这是一个可能的值。

具有 SP2 或更高版本的 Windows XP 支持此 协议 值。

IPPROTO_TCP
6
传输控制协议 (TCP) 。 当 af 参数AF_INET或AF_INET6且类型参数SOCK_STREAM时,这是一个可能的值。
IPPROTO_UDP
17
用户数据报协议 (UDP) 。 当 af 参数AF_INET或AF_INET6且类型参数SOCK_DGRAM时,这是一个可能的值。
IPPROTO_ICMPV6
58
Internet 控制消息协议版本 6 (ICMPv6) 。 当 af 参数 AF_UNSPEC、 AF_INET或 AF_INET6 且 类型 参数 SOCK_RAW 或未指定时,此值可能为 。

Windows XP 及更高版本支持此 协议 值。

IPPROTO_RM
113
可靠多播的 PGM 协议。 当 af 参数AF_INET且类型参数SOCK_RDM时,这是一个可能的值。 在针对 Windows Vista 及更高版本发布的 Windows SDK 上,此协议也称为 IPPROTO_PGM。

仅当安装了可靠多播 协议 时,才支持此协议值。

 

 

网络通信的核心机制:Socket如何实现高效数据传输 - 知乎 https://zhuanlan.zhihu.com/p/651684767

Socket并不是一种协议,可以将Socket理解为方便直接使用更底层协议(传输层TCP或UDP)而存在的一个抽象层。Socket跟TCP/IP协议没有必然的联系。Socket编程接口在设计的时候,就希望也能适应其他的网络协议,Socket只是使得用TCP/IP协议栈更方便而已。所以Socket是对TCP/IP协议的封装,它是一组接口。这组接口当然可以由不同的语言去实现。它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。用套接字中的相关函数来完成通信过程。

1.1Socket定义

套接字的特性有三个属性确定,它们是:域(domain),类型(type),和协议(protocol)。套接字还用地址作为它的名字。地址的格式随域(又被称为协议族,protocol family)的不同而不同。每个协议族又可以使用一个或多个地址族定义地址格式。

套接字的域:域指定套接字通信中使用的网络介质。最常见的套接字域是AF_INET,它是指Internet网络,许多Linux局域网使用的都是该网络,当然,因特网自身用的也是它。其底层的协议——网际协议(IP)只有一个地址族,它使用一种特定的方式来指定网络中的计算机,即IP地址。在计算机系统内部,端口通过分配一个唯一的16位的整数来表示,在系统外部,则需要通过IP地址和端口号的组合来确定。

套接字类型:流套接字(在某些方面类似域标准的输入/输出流)提供的是一个有序,可靠,双向字节流的连接。
流套接字由类型SOCK_STREAM指定,它们是在AF_INET域中通过TCP/IP连接实现的。他们也是AF_UNIX域中常见的套接字类型。

数据包套接字:与流套接字相反,由类型SOCK_DGRAM指定的数据包套接字不建立和维持一个连接。它对可以发送的数据包的长度有限制。数据报作为一个单独的网络消息被传输,它可能会丢失,复制或乱序到达。
数据报套接字实在AF_INET域中通过UDP/IP连接实现,它提供的是一种无需的不可靠服务。

套接字协议:只要底层的传输机制允许不止一个协议来提供要求的套接字类型,我们就可以为套接字选择一个特定的协议。

 

 

            func() {
                defer func() {
                    if e := recover(); e != nil {
                        log.Printf("recover: %v", e)
                    }
                }()
                err := os.RemoveAll(unix_domain_socket)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                laddr, err := net.ResolveUnixAddr("unixgram", unix_domain_socket)
                if err != nil {
                    fmt.Println(err)
                    return
                }
                conn, err := net.ListenUnixgram("unixgram", laddr)
                if err != nil {
                    fmt.Println("conn ", err)
                    return

                }
                for {
                    var buf = make([]byte, 1024)
                    _, raddr, err := conn.ReadFromUnix(buf)
                    if err != nil {
                        fmt.Println("ReadFromUnix ", err)
                        continue
                    }
                    recv := string(buf)
                    fmt.Println(recv)
                    _, err = conn.WriteToUnix([]byte("to client: "+recv+fmt.Sprintln(time.Now())), raddr)
                    fmt.Println(raddr)
                    if err != nil {
                        fmt.Println("WriteToUnix ", err)
                        // continue
                    }
                    func() {
                        // "value_air": 0.0, "longitude": 113.967931, "latitude": 22.594483}
                        type T struct {
                            Pubtime   string  `json:"pubtime"`
                            Time_data []Point `json:"time_data"`
                        }

                        func() {
                            // A5TDG000
                            defer func() {
                                if e := recover(); e != nil {
                                    log.Printf("recover: %v", e)
                                }
                            }()
                            mysqldsn := String(getConf("mysqldsn"))
                            db := getDBCli(mysqldsn)
                            defer db.Close()
                            q := `SELECT id_num,map_index,ret_data FROM nanshan_db.kriging_img WHERE img_list="" OR img_list IS NULL`
                            q = `SELECT id_num,map_index,ret_data FROM nanshan_db.kriging_img WHERE img_list IS NULL  `
                            // q = `SELECT id_num,map_index,ret_data FROM nanshan_db.kriging_img `
                            // q = `SELECT 1,MAP_INDEX,RET_DATA FROM KRIGING_IMG `
                            rows, err := db.Query(q)
                            fmt.Println(q)
                            if err != nil {
                                log.Println(err)
                                return
                            }
                            imgs_to_del := []string{}
                            for rows.Next() {
                                var id_num int64
                                var map_index, ret_data string

                                err := rows.Scan(&id_num, &map_index, &ret_data)
                                if err != nil {
                                    log.Println(err)
                                    continue
                                }
                                // log.Println(id_num, map_index, ret_data)
                                // DataString := "{\"K\":\"" + strings.ReplaceAll(ret_data, "\"", "\\\"") + "\"}"
                                // DataString := "{\"K\":" + ret_data + "}"
                                DataString := ret_data
                                // log.Println(DataString)
                                // i := T{}
                                i := []T{}
                                err = json.Unmarshal([]byte(DataString), &i)
                                if err != nil {
                                    log.Println(err)
                                    continue
                                }
                                // log.Println((i.K)[0])

                                // for _, one := range i.K {
                                target := map[string]string{}
                                for _, one := range i {
                                    k := KrigingRequestModel{}
                                    k.Boundary = bizConst.NanShanLatLon
                                    k.Index = map_index
                                    k.Points = one.Time_data
                                    log.Println("img_dir=", img_dir)
                                    img, err := GetKrigingPNG(k, img_dir)
                                    if err != nil {
                                        log.Println(err)
                                        //异常数据
                                        // continue
                                    }
                                    fmt.Println(img, err)
                                    target[one.Pubtime] = img_path_prefix + img
                                    fmt.Println(img_path_prefix+img, err)
                                    imgs_to_del = append(imgs_to_del, img_abs_dir+img_path_prefix+img)

                                }
                                e := "UPDATE nanshan_db.kriging_img SET img_list=?"
                                bs, err := json.Marshal(target)
                                if err != nil {
                                    log.Println(err)
                                    continue
                                }
                                _, err = db.Exec(e, string(bs))
                                if err != nil {
                                    log.Println(err)
                                    continue
                                }
                            }
                            go func() {
                                // time.After(time.Hour * 12)
                                for _, p := range imgs_to_del {
                                    log.Println(p)
                                    // os.Remove(p)
                                }
                            }()
                            time.Sleep(time.Second * 4)
                        }()
                    }()
                }
            }()
posted @ 2018-01-04 11:16  papering  阅读(179)  评论(0编辑  收藏  举报