代码改变世界

网络编程之socketserver初识

2018-02-23 10:59  親親宝贝  阅读(183)  评论(0编辑  收藏  举报
网络编程之socketserver初识
Server
#!/usr/bin/env python
# @Author   : "Wjl"
# @Date     : 2017/12/22
# @Time     : 11:07
# @SoftWare : PyCharm
# @File     : Server端并发聊天_Server.py

import socketserver

"""
socketserver模块是python为我们写好的一个封装了网络操作相关的模块
比我们自己手写socket方便
"""

class MyServer(socketserver.BaseRequestHandler):  # 必须继承socketserver.BaseRequestHandler

    def handle(self):  # 必须重写父类的handle方法,我们的逻辑就写在handle方法中
        print("服务端启动...")
        while True:
            conn = self.request  # self.request 就等于 TcpSocket.accept() 返回的socket对象
            print(self.client_address)  # self.client_address 就等于 TcpSocket.accept 返回的addr元组
            while True:
                # 将接收到的数据原路返回
                client_data = conn.recv(1024)
                print(str(client_data, "utf8"))
                print("waiting...")
                conn.sendall(client_data)
            conn.close()

if __name__ == '__main__':
    server = socketserver.ThreadingTCPServer(('127.0.0.1', 8888), MyServer)  # 要实现并发就必须调用ThreadingTCPServer
    server.serve_forever()  # 启动
View Code

 

Client
#!/usr/bin/env python
# @Author   : "Wjl"
# @Date     : 2017/12/22
# @Time     : 11:07
# @SoftWare : PyCharm
# @File     : Server端并发聊天_Client.py

import socket

TcpSocket = socket.socket()

TcpSocket.connect(('127.0.0.1', 8888))

while True:
    user_input = input('>>> ')
    if user_input == 'q':
        break

    TcpSocket.send(user_input.encode('utf-8'))
    data = TcpSocket.recv(1024)
    print(data.decode('utf-8'))

TcpSocket.close()
View Code