本地套接字
linux 文件:b(块设备文件) c(字符设备文件) d(目录) -(普通文件) l(连接) s(套接字) p(管道)
本地套接字作用:用于本地不同程序间进行通信
创建流程:
1.创建本地套接字
sockfd = socket(AF_UNIX,SOCK_STREAM)
2.绑定本地套接字文件
选定文件位置和名称
sockfd.bind(文件路径)
3.监听 sockfd.listen()
4.消息收发 recv send
os.path.exists(文件路径):判断一个文件是否存在,存在返回True,否则返回False
os.remove(文件路径):删除一个文件
代码示例:
准备文件:
unix_recv.py 用做服务端
unix_send.py 用做客户端
unix_recv.py代码:
from socket import *
import os
s_file = 'G:/Python/11111'
if os.path.exists(s_file):
os.remove(s_file)
s = socket(AF_UNIX,SOCK_STREAM)
s.bind(s_file)
s.listen(5)
while True:
c,addr = s.accept()
while True:
data = c.recv(1024)
if data:
print(data.decode())
c.send('收到你的消息'.encode())
else:
c.close()
break
s.close()
unix_send.py代码:
from socket import *
s_file = 'G:/Python/11111'
s = socket(AF_UNIX,SOCK_STREAM)
s.connect(s_file)
while True:
msg = input('->')
if msg:
s.send(msg.encode())
print(s.recv(1024).decode())
else:
break
s.close()
发表评论