• python 网络编程第四版


    使用SocketServer 模块来完成服务端编程

    1、服务端代码如下:

    #!/usr/bin/python
    #!coding:utf-8
    
    import SocketServer as socketserver
    
    class ClientHandler(socketserver.BaseRequestHandler):
        def handle(self):
            print '[info]    server has recive a connection :{0}'.format(self.client_address)
            while True:
                reciveData=self.request.recv(1024)
                if not reciveData:print '[info]    server the client has logout';break
                print '[info]    server has reviced this :{0}'.format(reciveData.decode())
                reply='this is the reply information form server -->{0}'.format(reciveData.decode())
                self.request.send(reply.encode())
    if __name__=="__main__":
        hostIp='127.0.0.1'
        port=2048
        server=socketserver.ThreadingTCPServer((hostIp,port),ClientHandler)
        server.serve_forever()
        

    2、客户端的代码如下:

    #!/usr/bin/python
    #!coding:utf-8
    
    from socket import *
    import os,sys
    
    if __name__ == "__main__":
        #定义套接字
        hostIp='127.0.0.1'
        port=2048
        sock=socket(AF_INET,SOCK_STREAM)
        messages=['hello I am a client']
        messages=messages+sys.argv[1:]
        sock.connect((hostIp,port))
        print '[info]    已经连接到server '
        
        for message in messages:
            sock.send(message.encode())
            print sock.recv(1024).decode()
        sock.close()
        
  • 相关阅读:
    POJ3320 Jessica's Reading Problem
    POJ3320 Jessica's Reading Problem
    CodeForces 813B The Golden Age
    CodeForces 813B The Golden Age
    An impassioned circulation of affection CodeForces
    An impassioned circulation of affection CodeForces
    Codeforces Round #444 (Div. 2) B. Cubes for Masha
    2013=7=21 进制转换
    2013=7=15
    2013=7=14
  • 原文地址:https://www.cnblogs.com/JiangLe/p/5095831.html
Copyright © 2020-2023  润新知