unix domain socket 淺析

unix domain socket

unix domain socket 是在socket架構上發展起來的用於同一臺主機的進程間通信(IPC: Inter-Process Communication),它不須要通過網絡協議棧,不須要打包拆包、計算校驗和、維護序號和應答等,只是將應用層數據從一個進程拷貝到另外一個進程。UNIX Domain Socket有SOCK_DGRAM或SOCK_STREAM兩種工做模式,相似於UDP和TCP,可是面向消息的UNIX Domain Socket也是可靠的,消息既不會丟失也不會順序錯亂。html

UNIX Domain Socket可用於兩個沒有親緣關係的進程,是全雙工的,是目前使用最普遍的IPC機制,好比X Window服務器和GUI程序之間就是經過UNIX Domain Socket通信的。python

UNIX Domain socket與網絡socket相似,能夠與網絡socket對比應用。linux

上述兩者編程的不一樣以下:程序員

  • address family爲AF_UNIX
  • 由於應用於IPC,因此UNIXDomain socket不須要IP和端口,取而代之的是文件路徑來表示「網絡地址」。這點體如今下面兩個方面。
  • 地址格式不一樣,UNIXDomain socket用結構體sockaddr_un表示,是一個socket類型的文件在文件系統中的路徑,這個socket文件由bind()調用建立,若是調用bind()時該文件已存在,則bind()錯誤返回。
  • UNIX Domain Socket客戶端通常要顯式調用bind函數,而不象網絡socket同樣依賴系統自動分配的地址。客戶端bind的socket文件名能夠包含客戶端的pid,這樣服務器就能夠區分不一樣的客戶端。

下面用python代碼演示uds的使用編程

Python代碼演示

服務端ubuntu

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 12/11/17 11:55 AM
@author: Chen Liang
@function: socket_echo_server_uds
"""

import sys

reload(sys)
sys.setdefaultencoding('utf-8')
import socket
import os

server_address = './uds_socket'

# Make sure the socket does not already exist
try:
    os.unlink(server_address)
except OSError:
    if os.path.exists(server_address):
        raise

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)

# Bind the socket to the address
print('starting up on {}'.format(server_address))
sock.bind(server_address)

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print('waiting for a connection')
    connection, client_address = sock.accept()
    try:
        print('connection from', client_address)

        # Receive the data in small chunks and retransmit it
        while True:
            data = connection.recv(16)
            print('received {!r}'.format(data))
            if data:
                print('sending data back to the client')
                connection.sendall(data)
            else:
                print('no data from', client_address)
                break

    finally:
        # Clean up the connection
        connection.close()

客戶端服務器

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Created on 12/11/17 11:55 AM
@author: Chen Liang
@function: socket_echo_client_uds
"""

import sys

reload(sys)
sys.setdefaultencoding('utf-8')


import socket
import sys

# Create a UDS socket
sock = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = './uds_socket'
print('connecting to {}'.format(server_address))
try:
    sock.connect(server_address)
except socket.error as msg:
    print(msg)
    sys.exit(1)

try:

    # Send data
    message = b'This is the message.  It will be repeated.'
    print('sending {!r}'.format(message))
    sock.sendall(message)

    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print('received {!r}'.format(data))

finally:
    print('closing socket')
    sock.close()

客戶端一次發送,服務端分批返回。網絡

服務端輸出結果以下架構

root@ubuntu:~/PycharmProjects/python_scripts# python socket_echo_server_uds.py 
starting up on ./uds_socket
waiting for a connection
('connection from', '')
received 'This is the mess'
sending data back to the client
received 'age.  It will be'
sending data back to the client
received ' repeated.'
sending data back to the client
received ''
('no data from', '')
waiting for a connection

客戶端輸出結果以下dom

root@ubuntu:~/PycharmProjects/python_scripts# python socket_echo_client_uds.py 
connecting to ./uds_socket
sending 'This is the message.  It will be repeated.'
received 'This is the mess'
received 'age.  It will be'
received ' repeated.'
closing socket

查看套接字文件的類型以下

root@ubuntu:~/PycharmProjects/python_scripts# ls -l ./uds_socket
srwxr-xr-x 1 root root 0 Dec 11 13:45 ./uds_socket

可見uds文件是socket類型。具體的linux文件類型有如下幾種:

Linux的文件類型有如下幾種:

文件類型 ls -l顯示
普通文件 -
目錄 d
符號連接 l
字符設備 c
塊設備 b
套接字 s
命名管道 p

參考:


記得幫我點贊哦!

精心整理了計算機各個方向的從入門、進階、實戰的視頻課程和電子書,按照目錄合理分類,總能找到你須要的學習資料,還在等什麼?快去關注下載吧!!!

resource-introduce

念念不忘,必有迴響,小夥伴們幫我點個贊吧,很是感謝。

我是職場亮哥,YY高級軟件工程師、四年工做經驗,拒絕鹹魚爭當龍頭的斜槓程序員。

聽我說,進步多,程序人生一把梭

若是有幸能幫到你,請幫我點個【贊】,給個關注,若是能順帶評論給個鼓勵,將不勝感激。

職場亮哥文章列表:更多文章

wechat-platform-guide-attention

本人全部文章、回答都與版權保護平臺有合做,著做權歸職場亮哥全部,未經受權,轉載必究!

相關文章
相關標籤/搜索