zoukankan      html  css  js  c++  java
  • 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()
        
  • 相关阅读:
    promise 理解
    强化学习的概念
    Ubuntu安装机器学习环境步骤
    jsp文件复制到web项目出错
    jdbc导致的问题
    C#窗体-猜数字
    软件工程结对作业01
    第二阶段冲刺10天 第3天进展报告
    第二阶段冲刺10天 第2天进展报告
    第二阶段冲刺10天 第1天进展报告
  • 原文地址:https://www.cnblogs.com/JiangLe/p/5095831.html
Copyright © 2011-2022 走看看