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()
  • 相关阅读:
    hdu 3342 Legal or Not 拓排序
    hdu 1596 find the safest road Dijkstra
    hdu 1874 畅通工程续 Dijkstra
    poj 2676 sudoku dfs
    poj 2251 BFS
    poj Prime Path BFS
    poj 3278 BFS
    poj 2387 Dijkstra 模板
    poj 3083 DFS 和BFS
    poj 1062 昂贵的聘礼 dijkstra
  • 原文地址:https://www.cnblogs.com/Lyue/p/7451964.html
Copyright © 2011-2022 走看看