• python网络编程


    #testser.py

    #coding=utf-8
    from socket import *
    from time import ctime
    
    HOST = ""
    PORT = 50000
    BUFSIZ = 1024
    ADDR = (HOST,PORT)
    
    # 套接字定义方法:socket(socket_family,socket_type,protocol = 0)
    # 套接字有两种:基于文件的AF_UNIX(AF_LOCAL为升级版)和基于网络的AF_INET
    # 每一种套接字都可以分为面向连接的SOCK_STREAM、无连接的SOCK_DGRAM
    tcpserversock = socket(AF_INET,SOCK_STREAM)
    # 绑定地址(主机名,端口)到套接字
    tcpserversock.bind(ADDR)
    # listen()表示最多允许多少个连接进来,而后的将被拒绝掉。
    tcpserversock.listen(5)
    
    while True:
        print "waiting for connection..."
        # accept() -> (socket object, address info) Wait for an incoming connection.  
        # Return a new socket representing the connection, and the address of the client.  
        # For IP sockets, the address info is a pair (hostaddr, port).
        tcpclientsock,addr = tcpserversock.accept()
        print "...connected from:",addr
    
        while True:
            # recv(buflen[, flags]) -- receive data
            data = tcpclientsock.recv(BUFSIZ)
            if not data:
                break
            tcpclientsock.send('[%s] %s'% (ctime(),data))
            if data == '':
                tcpclientsock.close()
    tcpserversock.close()
    
        
    

    #testcli.py

    from socket import *
    
    HOST = "127.0.0.1"
    PORT = 50000
    BUFSIZE = 1024
    ADDR = (HOST,PORT)
    
    socketclient = socket(AF_INET,SOCK_STREAM)
    socketclient.connect(ADDR)
    
    while True:
    	data = raw_input('>')
    	if not data:
    		break
    	socketclient.send(data)
    	data = socketclient.recv(BUFSIZE)
    	if not data:
    		break
    	print data
    	
    socketclient.close()
    

      

      

  • 相关阅读:
    CSS3实现平行四边形
    [Python]图的遍历-DFS
    [Python]图的遍历-BFS
    [Python]图的遍历-拓扑排序
    [Python]哈夫曼编码
    [Python]贪心算法-Prim-和-Kruskal实现-最小生成树
    [Python]贪心算法-Dijkstra-实现
    [python3]稳定匹配算法实现和优化
    从csv文件构建Tensorflow的数据集
    Tensorflow 基础API
  • 原文地址:https://www.cnblogs.com/hester/p/4713026.html
Copyright © 2020-2023  润新知