huazhi 发表于 2018-8-4 06:48:54

Python的简单socket操作

import socket  host = ''
  port = 12345
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  s.bind((host, port))
  s.listen(1)
  print "Server is running on port %d; press Ctrl-C to terminate." % port
  while 1:
  clientsock, clientaddr = s.accept()
  clientfile = clientsock.makefile('rw', 0)
  clientfile.write("Welcome, " + str(clientaddr) + "\n")
  clientfile.write("Please enter a string: ")
  line = clientfile.readline().strip()
  clientfile.write("Hello %s. ^_^ How are you Today! \n" % line)
  clientfile.close()
  clientsock.close()
  /// telnet localhost 12345
  Welcome, ('127.0.0.1', 3190)
  Please enter a string: woody
  Hello woody. ^_^ How are you Today!
  失去了跟主机的连接。
  C:\Documents and Settings\Administrator>
页: [1]
查看完整版本: Python的简单socket操作