1. 程式人生 > >Python socket 實現程序間通訊

Python socket 實現程序間通訊

基本用法

Python socket 使用方法如下

socket = socket.socket(family, type[, protocal])
  • family代表地址家族,一般為AF_UNIX,AF_INET和AF_INET6。AF_UNIX用於同一臺機器上的程序通訊,AF_INET用於IPV4協議的TCP和UDP,AF_INET6用於IPV6協議;
  • type代表套接字型別,一般為SOCK_STREAM,SOCK_DGRAM和SOCK_RAW。SOCK_STREAM為流式套接字,用於TCP通訊,SOCK_DGRAM為資料報式套接字,用於UDP通訊,SOCK_RAW為原始套接字,可以用於處理ICMP、IGMP等網路報文,這是普通套接字無法處理的;
  • protocal代表協議編號,預設為0。

本地程序間通訊例項

伺服器端:

import socket
import os

if __name__ == '__main__':
    server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    if os.path.exists("/tmp/test.sock"):
        os.unlink("/tmp/test.sock")
    server.bind("/tmp/test.sock")
    server.listen(0)
    while True:
        connection, address = server.accept
() connection.send("test: %s"% connection.recv(1024)) connection.close()

客戶端:

import socket
import os

if __name__ == '__main__':
    client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    client.connect("/tmp/test.sock")

    instr = raw_input()
    client.send(instr)
    print
client.recv(1024) client.close()

遠端程序間通訊例項

伺服器端:

import socket
import os

if __name__ == '__main__':
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind(("localhost", 8888))
    server.listen(0)
    while True:
        connection, address = server.accept()
        connection.send("test: %s"% connection.recv(1024))
    connection.close()

客戶端:

import socket
import os

if __name__ == '__main__':
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(("localhost", 8888))

    instr = raw_input()
    client.send(instr)
    print client.recv(1024)

    client.close()