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也是可靠的,消息既不會丟失也不會順序錯亂。

UNIX Domain Socket可用於兩個沒有親緣關系的進程,是全雙工的,是目前使用最廣泛的IPC機制,比如X Window服務器和GUI程序之間就是通過UNIX Domain Socket通訊的。

UNIX Domain socket與網絡socket類似,可以與網絡socket對比應用。

上述二者編程的不同如下:

  • 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代碼演示

服務端

#!/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

客戶端輸出結果如下

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

本人所有文章、回答都與版權保護平台有合作,著作權歸職場亮哥所有,未經授權,轉載必究!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM