先看socket多并发的服务端的代码,这里是用多线程实现的多并发socketserver
import socketserver # socketserver有四个基本的类,后两个不常用,这4个类处理并发请求都是同步的,他们其实不是多线程的,他们只是把socke封装了一下,加了一些方法,这里还没有实现多并发和多线程 #这些方法不适用每个请求都耗费长时间才能完成 # socketserver.TCPServer # socketserver.UDPServer # socketserver.UnixStreamServer # socketserver.UnixDatagramServer # socketserver.ForkingMixIn # socketserver.ThreadingMixIn # ======================================================================================================== # 我们真正要用的下面这4个方法 # 多进程的socketserver # socketserver.ForkingTCPServer # socketserver.ForkingUDPServer #多进程的socketserver # socketserver.ThreadingTCPServer # socketserver.ThreadingUDPServer # ======================================================================================================== class MyTcpServerClass(socketserver.BaseRequestHandler): # 先定义一个自己的socket的类,所有和客户端交互的动作全部要在这里写,默认这里是空白的,且必须写handle这个防范 def handle(self): print("等待新的连接:") print("新的客户端:",self.client_address) while True: try: data = self.request.recv(1024) print("客户端:",self.client_address,str(data,encoding="utf-8")) self.request.send(data) except Exception: print("客户端[%s]连接已经断开,服务端也将断开" %(self.client_address[1])) self.request.close() break if __name__ == '__main__': ip_bind = ("127.0.0.1",9000) server = socketserver.ThreadingTCPServer(ip_bind,MyTcpServerClass) # 每次来一个连接,就构建一个实例 server.serve_forever() # 让这个server一直运行
然后看下客户端的代码
import socket ip_bind = ("127.0.0.1",9000) c = socket.socket() c.connect(ip_bind) while True: c_input = input("客户端:") c.send(bytes(c_input,encoding="utf-8")) s_send = c.recv(1024) print("服务端:",str(s_send,encoding="utf-8"))
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/20878.html