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()
  • 相关阅读:
    eclipse自动生成uml
    【北航软件工程】Alpha阶段前端页面编写及服务器部署
    【北航软件工程】最长单词链
    软件工程第一次阅读!
    软工第0次个人作业
    第四次oo博客
    小菜鸡儿的第三次OO博客
    关于面向对象第二阶段的总结
    关于面向对象第一阶段的总结
    `ll/sc` 指令在`linux`中的软件实现
  • 原文地址:https://www.cnblogs.com/Lyue/p/7451964.html
Copyright © 2011-2022 走看看