---------------------------server.py---------------------
import socketserver
class MyServer(socketserver.BaseRequestHandler):
#MServer类 继承socketserver.BaseRequestHandler类
def handle(self):#它内部封装的是建立连接的这个逻辑过程
#重写handle,必须叫handle方法,因为它是父类的一个方法
print ("服务端启动...")
while True:
conn = self.request
#拿客户端的通道,它内部把这个过程附给request变量
print (self.client_address)
while True:
client_data=conn.recv(1024)
print (str(client_data,"utf8"))
print ("waiting...")
server_response=input(">>>")
conn.sendall(bytes(server_response,"utf8"))
# conn.sendall(client_data)
conn.close()
# print self.request,self.client_address,self.server
if __name__ == '__main__':
server = socketserver.ThreadingTCPServer(('127.0.0.1',8011),MyServer)
#调用socketserver模块的ThreadingTCPServer类目的实现并发效果
#而参数就是ip+port和你定义的类---这样就完成了封装
server.serve_forever() #通过此方法启动,它执行的是handle里边的内容
----------------------client.py-----------------------
import socket
ip_port = ('127.0.0.1',8011)
sk = socket.socket()
sk.connect(ip_port)
print ("客户端启动:")
while True:
inp = input('>>>')
sk.sendall(bytes(inp,"utf8"))
server_response=sk.recv(1024)
print (str(server_response,"utf8"))
if inp == 'exit':
break
sk.close()