zoukankan      html  css  js  c++  java
  • python 网络编程 (完成server/client 之间的通信)

    1、server(服务器)端的代码:

    #!/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)
        sock.bind((hostIp,port))
        sock.listen(5)
        print '[info]    开始监听{0}:{1}'.format(hostIp,port)
        while True:
            #接受一个客户端的连接
            conn,addr = sock.accept()
            print '[info]    has recived a client from {0}'.format(addr)
            #与客户端进行交互,直到客户端退出
            while True:
                #接收客户端发来的信息,一次最多收1024字节
                recivedData=conn.recv(1024)
                #由于客户端在断开时会发送一个空串,所以我们用这个上来测试连接是否断开
                if not recivedData : print '[wan]    客户端已经断开连接...'; break;
                print '[info]    this is a infomation from client --> {0}'.format(recivedData.decode())
                #发送信息到客户端
                conn.send('this inforamtion from server --> {0}'.format(recivedData.decode()).encode())
            conn.close()

    2、client(客服端)端的代码:

    #!/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()
  • 相关阅读:
    FastDFS集群安装说明
    关于Sentaurus的日常(一)(Basics)
    关于Sentaurus的日常(三)
    记录程序运行时间之clock 函数
    Mysql 使用经验 2013
    proxy ip 收集方式总结
    操作系统的默认格式的陷阱
    VNC server 使用手记
    div body 间距
    asp.net处女作
  • 原文地址:https://www.cnblogs.com/Lyue/p/7451964.html
Copyright © 2011-2022 走看看