zoukankan      html  css  js  c++  java
  • 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()
    

      

      

  • 相关阅读:
    小程序对象属性赋值
    'cross-env' 不是内部或外部命令,也不是可运行的程序
    npm太慢, 淘宝npm镜像使用方法
    git设置忽略文件.gitignore
    小程序报错 Please do not register multiple Pages in undefined.js
    小程序监听滚动条
    获取动态元素高度
    小程序BUTTON点击,去掉背景色
    封装token
    JS删除对象属性
  • 原文地址:https://www.cnblogs.com/hester/p/4713026.html
Copyright © 2011-2022 走看看