python如何创建TCP服务端和客户端

作者:卖鱼熊 时间:2021-05-20 04:52:52 

本文实例为大家分享了python创建tcp服务端和客户端的具体代码,供大家参考,具体内容如下

1.服务端server


from socket import *
from time import ctime

HOST = ''
PORT = 9999
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)  #创建套接字
tcpSerSock.bind(ADDR)  #绑定IP和端口
tcpSerSock.listen(5)  #监听端口,最多5人排队

while True:
 print('waiting for connection...')
 tcpCliSock, addr = tcpSerSock.accept()  #建立连接
 print('...connected from:', addr)

while True:
   data = tcpCliSock.recv(BUFSIZ)
   if not data:
     break
   content = '[%s] %s' % (bytes(ctime(), "utf-8"), data)
   print(data)
   print(type(content))
   tcpCliSock.send(content.encode("utf-8"))

tcpCliSock.close()

tcpSerSock.close()

2.客户端client


from socket import *

HOST = '127.0.0.1' # or 'localhost'
PORT = 9999
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
 data = input('> ')
 if not data:
   break

tcpCliSock.send(data.encode("utf-8"))
 data = tcpCliSock.recv(BUFSIZ)
 if not data:
   break
 print(data.decode("utf-8"))

tcpCliSock.close()

来源:https://www.cnblogs.com/Selling-fish-bears/archive/2018/08/26/9537151.html

标签:python,服务端,客户端
0
投稿

猜你喜欢

  • php简单实现批量上传图片的方法

    2023-11-20 13:55:53
  • 编写数据库asp程序需注意的问题

    2007-12-29 12:57:00
  • python中使用xlrd、xlwt操作excel表格详解

    2023-06-25 03:59:51
  • SQL Server从安装到建库为新手寻找捷径

    2009-01-13 13:22:00
  • mysql慢查询的分析方法

    2010-08-03 14:51:00
  • Python常见MongoDB数据库操作实例总结

    2023-07-08 08:48:34
  • 丰富段落里的标签

    2008-03-16 14:11:00
  • 一个简单的 js 上滚信息栏

    2013-08-07 03:26:30
  • SQL语句的执行原理分析

    2012-01-29 18:17:36
  • MYSQL教程:服务器优化和硬件优化

    2009-02-27 15:43:00
  • 在Python中使用NLTK库实现对词干的提取的教程

    2022-11-04 15:13:53
  • 解决SQL Server日志文件损坏严重的问题

    2009-02-05 15:55:00
  • asp fso操作类

    2011-03-07 10:57:00
  • Python采集情感音频的实现示例

    2023-06-11 23:17:10
  • Python性能优化技巧

    2021-06-29 12:48:32
  • Python seaborn barplot画图案例

    2023-11-07 00:50:55
  • asp连接各种数据库代码

    2008-03-11 11:16:00
  • SQL语句练习实例之五 WMS系统中的关于LIFO或FIFO的问题分析

    2011-11-03 16:59:59
  • Echarts.js无法引入问题解决方案

    2023-08-12 22:57:26
  • 一篇文章彻底搞懂Python中可迭代(Iterable)、迭代器(Iterator)与生成器(Generator)的概念

    2023-11-03 23:52:38
  • asp之家 网络编程 m.aspxhome.com