day8--socketserver回顾

Posted (野生程序员)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了day8--socketserver回顾相关的知识,希望对你有一定的参考价值。

    sockeserver主要实现多并发的情况,我们知道,socket只能一对一用户进行交互,如何实现一对多交互,socketserver就是用来解决这个问题的。

    socketserver--共有这么几种类型:

    TCPServer:TCPServer类别的,都是socket。

    UDPServer:适用于UDP协议下。

    1、class socketserver.TCPServer(server_address,RequestHandlerClass,bind_and_activate=True)

    2、class socketserver.UDPServer(server_address,RequestHandlerClass,bind_and_activate=True)

    3、calss sockstserver.UnixStreamServer(server_address,RequestHandlercalss,bind_and_activate=True)

    4、class socketserver.UnixDatagramServer(server_address,RequestHandlerClass,bind_and_activate=True)

    创建一个socketserver 至少分以下几步:

    1、必须创建一个RequsetHandlerClass的类,而且必须重写父类里面handle()方法;

    2、必须声明一个处理请求:

    (1)server.handle_request()    只处理一个请求

    (2)server.serve_forever()     处理多个请求,永远执行。

    基本的socketserver代码

 

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print("{} wrote:".format(self.client_address[0]))
        print(self.data)
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

 

    socketserver其实与socket一样,只是socketserver能够实现一对多的交互,下面来看一个简单实例:

    服务器端:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
# self.request is the TCP socket connected to the client
while True:
self.data = self.request.recv(1024).strip()
if len(self.data) == 0:
break
print("{} wrote:".format(self.client_address[0]))
print(self.data)
print("地址:",self.client_address)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())

if __name__ == "__main__":
HOST, PORT = "0.0.0.0", 9994

# Create the server, binding to localhost on port 9999
#server = socketserver.TCPServer((HOST,PORT),MyTCPHandler) #socket方式,与socket一样,一对一
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler) #多线程方式进行一对多交互
#server = socketserver.ForkingTCPServer((HOST,PORT),MyTCPHandler) #多进程方式进行一对多交互

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

    socketserver的三种方式:

    TCPServer:实现和socket一样的功能,也是一对一;

    ThreadingTCPServer:多线程,一对多的形式;

    ForKingTCPServer:多进程;一对多的形式,多并发。

    客户端:

import socket

class Myclient(object):
    def __init__(self):
        self.client = socket.socket()

    def connect(self,ip,port):
        self.client.connect((ip,port))

    def interactive(self):
        while True:
            mess = input(">>:").strip()
            if len(mess) == 0:
                print("不能发送空的数据")
                continue
            self.client.send(mess.encode("utf-8"))
            data = self.client.recv(1024).decode("utf-8")
            print(data)

if __name__ == "__main__":
    client = Myclient()
    client.connect("localhost",9999)
    client.interactive()

    socketserver中,所有的功能都封装到了handle()方法里面,上面启动服务器之后,可以启动多个客户端,交流如下:

    服务器端的交互情况:

127.0.0.1 wrote:
basfda
地址: (127.0.0.1, 49256)
127.0.0.1 wrote:
bgagds
地址: (127.0.0.1, 49254)
127.0.0.1 wrote:
b\xe6\x88\x91\xe4\xbb\xac
地址: (127.0.0.1, 49254)
127.0.0.1 wrote:
b\xe9\x83\xbd\xe6\x98\xaf
地址: (127.0.0.1, 49254)
127.0.0.1 wrote:
b\xe5\xa5\xbd\xe5\x93\x88
地址: (127.0.0.1, 49254)
127.0.0.1 wrote:
bshibushi
地址: (127.0.0.1, 49252)
127.0.0.1 wrote:
b\xe6\x98\xaf\xe5\x91\x80\xef\xbc\x8c\xe9\x83\xbd\xe6\x98\xaf\xe4\xb8\x80\xe6\xa0\xb7
地址: (127.0.0.1, 49252)

    可以看出,实现了多并发,连接了3个不同的端口。

    self.client_address输出是:(127.0.0.1, 49252),可见,self.client_address是有IP和PORT(端口号)组成的。

    socketserver的三种交互方式,刚才还忘记了,一定要知道,如何用socketserver实现多并发。

 

 

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
"""
The request handler class for our server.

It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""

def handle(self):
# self.request is the TCP socket connected to the client
while True:
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
print("地址:",self.client_address)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())

if __name__ == "__main__":
HOST, PORT = "localhost", 9999

# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()

以上是关于day8--socketserver回顾的主要内容,如果未能解决你的问题,请参考以下文章

day8--socketserver

day8--socketserver作业

中国航信开发者大会(第一届)精彩回顾

回顾这些年的学习技术经历

JSP回顾

跪求2011年终回顾166部电影大混剪里面的音乐名及各部电影名称