unix dgram通信

# 同一个机器多个进程间通信,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()

相关推荐

  1. Socket通信

    2023-12-09 02:22:01       66 阅读
  2. linux通信

    2023-12-09 02:22:01       51 阅读
  3. Netlink通信

    2023-12-09 02:22:01       50 阅读
  4. SPI<span style='color:red;'>通信</span>

    SPI通信

    2023-12-09 02:22:01      54 阅读
  5. TCP<span style='color:red;'>通信</span>

    TCP通信

    2023-12-09 02:22:01      30 阅读
  6. 计算机通信

    2023-12-09 02:22:01       29 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-09 02:22:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-09 02:22:01       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-09 02:22:01       87 阅读
  4. Python语言-面向对象

    2023-12-09 02:22:01       96 阅读

热门阅读

  1. 3-Mybatis

    3-Mybatis

    2023-12-09 02:22:01      60 阅读
  2. Linux C++ 贪吃蛇游戏 -- 方向键控制蛇移动

    2023-12-09 02:22:01       58 阅读
  3. SkyPile-150B 数据下载地址

    2023-12-09 02:22:01       55 阅读
  4. Spring中拦截WebSecurityConfigurerAdapter和Aop拦截区分

    2023-12-09 02:22:01       60 阅读
  5. 计算三位数每位上数字的和

    2023-12-09 02:22:01       58 阅读
  6. 理想中的PC端剪切板工具,应该有哪些功能?

    2023-12-09 02:22:01       67 阅读