python从网络端口读取文本数据

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
# To test it with netcat, start the script and execute:
#
#    echo "Hello, cat." | ncat.exe 127.0.0.1 12345
#
import socket
 
HOST = 'localhost'   # use '' to expose to all networks
PORT = 12345
 
def incoming(host, port):
  """Open specified port and return file-like object"""
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  # set SOL_SOCKET.SO_REUSEADDR=1 to reuse the socket if
  # needed later without waiting for timeout (after it is
  # closed, for example)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  sock.bind((host, port))
  sock.listen(0)   # do not queue connections
  request, addr = sock.accept()
  return request.makefile('r', 0)
# /-- network ---
 
 
for line in incoming(HOST, PORT):
  print line,

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:urllib2使用代理服务器

下一篇:python之花瓣美女下载