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()
        
  • 相关阅读:
    python中文编码
    Python习题纠错1
    Python中的变量
    Python之注释
    python初步学习
    java输入数据并排序
    五月最后一天
    @component注解
    多线程回顾
    赖床分子想改变--
  • 原文地址:https://www.cnblogs.com/JiangLe/p/5095831.html
Copyright © 2011-2022 走看看