zoukankan      html  css  js  c++  java
  • python 网络编程第一版

    --version 1.0 只完成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()
        
  • 相关阅读:
    IOS:接口返回包含转义字符去掉转义字符
    properties和yml进行对比
    IDEA安装插件时搜索不到,一直在转圈刷新,无法安装
    VMware 15 虚拟机黑屏问题
    扩容根分区
    CentOS 6 各种启动文件损坏及修复
    RabbitMQ面试题
    FTP,SFTP服务器登录权限和根目录的设置
    Tee命令的几个使用实例
    ssh-copy-id 后无法免密登录
  • 原文地址:https://www.cnblogs.com/JiangLe/p/5094651.html
Copyright © 2011-2022 走看看