# 同一个机器多个进程间通信unix比AF_INET效率更高
# client
import socket               # 导入 socket 模块
import os
import threading
import time

class SocketClient(threading.Thread):
    def __init__(self):
        super(SocketClient, self).__init__()
        
        self._addr = "/tmp/socket/unix_socket"
        self._socket = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_DGRAM)         # 创建 socket 对象

    def connect(self):
        self._socket.connect(self._addr)

    def run(self):
        while True:
            msg = "hello, I am is client socket"
            self._socket.sendall(msg.encode())
            # msg = self._socket.recv(1024)
            # print(f"client recv msg:{msg.decode()}")
            time.sleep(1)

if __name__ == "__main__":
    try:
        client = SocketClient()                
        client.connect()
    except Exception as e:
        print(f"exception {e}")
    else:
        client.start()
# server
import socket               # 导入 socket 模块
import os
import threading
import time

class SocketServer(threading.Thread):
    def __init__(self):
        super(SocketServer, self).__init__()
        
        # 使用socket文件进行单项通信数据类型
        self._addr = "/tmp/socket/unix_socket"
        self._socket = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_DGRAM)         # 创建 socket 对象


    def bind(self):
        if os.path.exists(self._addr):
            os.unlink(self._addr)
        self._socket.bind(self._addr)

    def run(self):
        while True:
            msg = self._socket.recv(1024)
            print(f"server recv msg:{msg.decode()}")
            # self._socket.sendall(msg.encode())
            time.sleep(1)

if __name__ == "__main__":
    try:
        server = SocketServer()                
        server.bind()
    except Exception as e:
        print(f"exception {e}")
    else:
        server.start()

原文地址:https://blog.csdn.net/CodeHouse/article/details/134754515

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_37842.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注