python 创建一个TCP服务器

2022-06-05  本文已影响0人  孙广宁
11.2创建一个通过TCP协议通客户端进行通信的服务器
from socketserver import BaseRequestHandler,TCPServer

class EcoHandler(BaseRequestHandler):
    def handle(self):
        print("Got connection from",self.client_address)
        while True:
            msg = self.request.recv(8192)
            if not msg:
                break
            self.request.send(mgs)


if __name__ == '__main__':
    serv =TCPServer(('',2000),EchoHandler)
    serv.serve_forver()
>>> from socket import socket,AF_INET,SOCK_STREAM
>>> s = socket(AF_INET,SOCK_STREAM)
>>> s.connect(('localhost',20000))
>>> s.send(b'hello')
5
>>> s.recv(8192)
b'hello'
>>>
from socketserver import StreamRequestHandler,TCPServer

class EchoHandler(StreamRequestHandler):
    def handle(self):
        print("Got connection from",self.client_address)
        for line in self.rfile:
            self.wfile.write(line)

if __name__ == '__main__':
    serv =TCPServer(('',20000),EchoHandler)
    serv.serve_forever()
if __name__ == '__main__':
    serv =ThreadingTCPServer(('',20000),EchoHandler)
    serv.serve_forever()
~/ning-dashboard/tmp > python3 sockettest.py                                                                               10s
Got connection from ('127.0.0.1', 54186)
Got connection from ('127.0.0.1', 54292)
上一篇 下一篇

猜你喜欢

热点阅读