python之socket编程4

1 socketserver实现并发

基于tcp的套接字,关键是两个循环,一个通信循环,一个链接循环

Socketserver的 模块中分成两类:

   Server类(解决连接问题)

   Request类(解决通信问题)

server类:

request类:

继承关系:

#服务端
import socketserver
class FTPserver(socketserver.BaseRequestHandler):
    #定义一个类,继承socketserver.BaseRequestHandler
    #通讯
    def handle(self):#规定一个handle   规定死的
        print(self.request)#客户端的连接信息
        while True:#通信循环
            data=self.request.recv(1024)
            print(data)
            self.request.send(data.upper())
if __name__ == '__main__':
    obj=socketserver.ThreadingTCPServer(("127.0.0.1",8080),FTPserver)#基于多线程实现并发
    #产生一个对象
obj.serve_forever()#连接循环

#客户端
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(("127.0.0.1",8080))
while True:
    msg=input(">>")
    if not msg:continue
    phone.send(msg.encode("utf8"))
    data=phone.recv(1024)
print(data)
>>
<socket.socket fd=476, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 56456)>
<socket.socket fd=408, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 56457)>
<socket.socket fd=436, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 8080), raddr=('127.0.0.1', 56461)>
b'111'
b'2'
b'22'

2套接字工作流程(udp)

UDP:用户数据报协议

      是无连接的

面向消息的

不会产生粘包

Udp是不可靠传输

#服务端
import socket
udpserver=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udpserver.bind(("127.0.0.1",8080))
#udp没有链接,不用listen,accpect
while True:#通讯循环
    data,client_addr=udpserver.recvfrom(1024)
    print(data)
    print(client_addr)
    msg=input(">>")
    udpserver.sendto(msg,client_addr)

#客户端
import socket
udpclient=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
ip_port=(("127.0.0.1",8080))
while True:
    inp=input(">>")
    udpclient.sendto(inp.encode("utf8"),ip_port)

    data,server_addr=udpclient.recvfrom(1024)
print(data.decode("utf8"))

udp的socketserver并发
#服务端
import socketserver
class FtpServer(socketserver.BaseRequestHandler):
    def handle(self):
        print(self.request[0])
        print(self.request[1])
        self.request[1].sendto('嘎嘎嘎'.encode('utf-8'),self.client_address)

if __name__ == '__main__':
    obj=socketserver.ThreadingUDPServer(('127.0.0.1',8080),FtpServer)
obj.serve_forever()
#客户端
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))

while True: #通信循环
    msg=input('>>: ').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8'))
    # print('has send===========>')
    data=phone.recv(1024)
    # print('has recv===========>')
    print(data)

phone.close()

  

posted @ 2017-05-07 13:41  qianxiamo  阅读(258)  评论(0编辑  收藏  举报