# 同一个机器多个进程间通信,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进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。