您的位置:时时app平台注册网站 > 编程知识 > python底工之Socket并发

python底工之Socket并发

2019-11-28 03:14

client.py

server.py
import socketserver
class MyServer(socketserver.BaseRequestHandler):
#重写父类的主意
def handle(self):
print('waiting.......')
while 1:
conn= self.request
print(self.client_address)
while 1:
try:
data = conn.recv(1024)
except Exception:
break
if not data: break
print('......', str(data, 'utf8'))
inp = input('》》》》》》》》')
conn.sendall(bytes(inp, 'utf8'))
conn.close()
if name=='main':
server=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)
server.serve_forever()

 1 import socketserver
 2 
 3 class MyServer(socketserver.BaseRequestHandler):
 4     def handle(self):    #  里面是每个客户端连接执行的过程
 5         print('服务器启动')
 6         while True:
 7             conn = self.request
 8             print(self.client_address)
 9             while True:
10                 client_data = conn.recv(1024)
11                 print(str(client_data,'utf8'))
12                 print('waiting...')
13                 conn.sendall(client_data)
14             conn.close()
15 
16 if __name__ == '__main__':
17     server = socketserver.ThreadingTCPServer(('127.0.0.1',8888),MyServer)
18     server.serve_forever()       # 激活这个服务器对象

while True:
inp=input('>>>>>>>>>n')
if inp=='exit':
break
sk.send(bytes(inp,'utf8'))
data=sk.recv(1024)
print(str(data,'gbk'))
sk.close()

图片 1图片 2

client.py
import socket
sk=socket.socket()
address=('127.0.0.1',8080)
sk.connect(address)

得以完成产出闲聊:
1、继承socketserver.BaseRequestHandler
2、使用socketserver.ThreadingTCPServer(('127.0.0.1',8888),MyServer)取得三个服务器对象


图片 3图片 4

server.py

 

要相互发送新闻,能够在handle方法里面改成这些,这里的闲聊依然有那叁个可惜

 1 import  socket
 2 
 3 def connect_server():
 4     sk = socket.socket()
 5     server_address = ('127.0.0.1',8888)
 6     sk.connect(server_address)
 7     return sk
 8 
 9 if __name__ == '__main__':
10     sk = connect_server()
11     while True:
12         inp = input('>>>')
13         if inp == 'exit':
14             break
15         sk.send(bytes(inp,'utf8'))
16         print('waiting...')
17         data = sk.recv(1024)
18         print(str(data,'utf8'))
19     sk.close()

温馨调式一下这么些实施进度,看python的兑现源码

图片 5

本文由时时app平台注册网站发布于编程知识,转载请注明出处:python底工之Socket并发

关键词: