[Python] python从网络端口读取文本数据 →→→→→进入此内容的聊天室

来自 , 2021-03-19, 写在 Python, 查看 150 次.
URL http://www.code666.cn/view/d4ec33c0
  1. # To test it with netcat, start the script and execute:
  2. #
  3. #    echo "Hello, cat." | ncat.exe 127.0.0.1 12345
  4. #
  5. import socket
  6.  
  7. HOST = 'localhost'   # use '' to expose to all networks
  8. PORT = 12345
  9.  
  10. def incoming(host, port):
  11.   """Open specified port and return file-like object"""
  12.   sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  13.   # set SOL_SOCKET.SO_REUSEADDR=1 to reuse the socket if
  14.   # needed later without waiting for timeout (after it is
  15.   # closed, for example)
  16.   sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  17.   sock.bind((host, port))
  18.   sock.listen(0)   # do not queue connections
  19.   request, addr = sock.accept()
  20.   return request.makefile('r', 0)
  21. # /-- network ---
  22.  
  23.  
  24. for line in incoming(HOST, PORT):
  25.   print line,
  26. #//python/5788

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

这儿你可以回复上面这条便签

captcha