python--socketserver
Posted traditional
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python--socketserver相关的知识,希望对你有一定的参考价值。
服务端
import socketserver class Myserver(socketserver.BaseRequestHandler): ‘‘‘ 定义一个类,该类必须继承socketserver下的BaseRequestHandler ‘‘‘ def handle(self): # 重写其内部的handler方法 # 内部封装了self.request,就相当于socket当中的conn while True: recv = self.request.recv(1024) # 接受到字节形式的内容 if not recv: break print(str(recv, encoding="utf-8")) self.request.send(recv+bytes("我是你爸", encoding="utf-8")) # 创建多任务server,每来一个连接我就创建一个线程与其交互 server = socketserver.ThreadingTCPServer(("localhost", 8080), Myserver) server.serve_forever()
客户端1
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 8080))
while True:
inp = input("请输入你要发送的内容:")
client.send(bytes(inp, encoding="utf-8"))
recv = client.recv(1024)
print(str(recv, encoding="utf-8"))
客户端2
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 8080))
while True:
inp = input("请输入你要发送的内容:")
client.send(bytes(inp, encoding="utf-8"))
recv = client.recv(1024)
print(str(recv, encoding="utf-8"))
客户端3
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("localhost", 8080))
while True:
inp = input("请输入你要发送的内容:")
client.send(bytes(inp, encoding="utf-8"))
recv = client.recv(1024)
print(str(recv, encoding="utf-8"))
以上是关于python--socketserver的主要内容,如果未能解决你的问题,请参考以下文章
python------SocketServer (0809)