当前位置:   article > 正文

python socket 创建tcp服务器和客户端_puthon socket tcp

puthon socket tcp
1. server
  1. from socket import *
  2. from time import ctime
  3. HOST = ""
  4. PORT = 21567
  5. BUFSIZ = 1024
  6. ADDR = (HOST, PORT)
  7. tcpSerSock = socket(AF_INET, SOCK_STREAM)
  8. tcpSerSock.bind(ADDR)
  9. tcpSerSock.listen(5)
  10. while True:
  11. print("waiting for connection...")
  12. tcpCliSock, addr = tcpSerSock.accept()
  13. print("connected from :", addr)
  14. while True:
  15. data = tcpCliSock.recv(BUFSIZ)
  16. if not data:
  17. break
  18. content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
  19. print(data)
  20. print(type(content))
  21. tcpCliSock.send(content.encode("utf-8"))
  22. tcpCliSock.close()
  23. tcpSerSock.close()

2.client

  1. from socket import *
  2. HOST = "127.0.0.1"
  3. PORT = 21567
  4. BUFSIZ = 1024
  5. ADDR = (HOST, PORT)
  6. tcpCliSock = socket(AF_INET, SOCK_STREAM)
  7. tcpCliSock.connect(ADDR)
  8. while True:
  9. data = input("> ")
  10. if not data:
  11. break
  12. tcpCliSock.send(data.encode("utf8"))
  13. data = tcpCliSock.recv(BUFSIZ)
  14. if not data:
  15. break
  16. print(data.decode("utf-8"))
  17. tcpCliSock.close()


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/1013404
推荐阅读
相关标签
  

闽ICP备14008679号