python实现TCP服务器端与客户端的方法详解

作者:露露 时间:2023-05-17 09:39:39 

本文实例讲述了python实现TCP服务器端与客户端的方法。分享给大家供大家参考。具体如下:

TCP服务器程序(tsTserv.py):


from socket import *
from time import ctime
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(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
   tcpCliSock.send('[%s] %s' %(ctime(), data))
 tcpCliSock.close()
tcpSerSock.close()

TCP客户端程序(tsTclnt.py):


from socket import *
HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
tcpCliSock = socket(AF_INET, SOCK_STREAM)
tcpCliSock.connect(ADDR)
while True:
 data = raw_input('> ')
 if not data:
   break
 tcpCliSock.send(data)
 data1 = tcpCliSock.recv(BUFSIZ)
 if not data1:
   break
 print data1
tcpCliSock.close()

运行说明:先运行服务器程序,作用类似于打开服务器保持等待客户请求,再运行客户端程序。

运行界面如下:

服务器端:


D:\code\ex>python tsTserv.py
waiting for connection...
...connected from: ('127.0.0.1', 2883)
waiting for connection...
...connected from: ('127.0.0.1', 2885)
waiting for connection...
...connected from: ('127.0.0.1', 2889)
waiting for connection...
...connected from: ('127.0.0.1', 2891)
waiting for connection...
...connected from: ('127.0.0.1', 2892)
waiting for connection...
...connected from: ('127.0.0.1', 2893)
waiting for connection...

客户端:


D:\code\ex>python tsTclnt.py
> 1
[Thu Feb 02 15:52:21 2012] 1
> 2
[Thu Feb 02 15:52:22 2012] 2
> 3
[Thu Feb 02 15:52:22 2012] 3
> 5
[Thu Feb 02 15:52:23 2012] 5
> 6
[Thu Feb 02 15:52:24 2012] 6
>
D:\code\ex>

希望本文所述对大家的Python程序设计有所帮助。

标签:python,TCP
0
投稿

猜你喜欢

  • Python之lxml安装失败的解决

    2023-11-27 04:34:22
  • python利用小波分析进行特征提取的实例

    2023-01-02 01:02:22
  • python的scikit-learn将特征转成one-hot特征的方法

    2022-06-21 11:34:29
  • Linux下docker安装mysql8并配置远程连接

    2024-01-18 15:53:43
  • Python实现机器学习算法的分类

    2023-08-31 05:50:36
  • Python中让MySQL查询结果返回字典类型的方法

    2024-01-25 04:37:33
  • Python全局变量global关键字详解

    2023-01-29 22:32:50
  • python实现ftp文件传输功能

    2023-04-21 13:20:16
  • 详解python异步编程之asyncio(百万并发)

    2022-05-09 04:44:12
  • Prometheus开发中间件Exporter过程详解

    2023-04-18 16:14:13
  • IE6终极备忘单——对IE6单独兼容[译]

    2010-01-21 18:34:00
  • Pytorch损失函数torch.nn.NLLLoss()的使用

    2021-02-07 16:08:57
  • Pytorch实现Fashion-mnist分类任务全过程

    2023-07-14 05:12:47
  • 用蜜罐来阻止垃圾评论

    2007-11-06 12:35:00
  • python通过re正则表达式切割中英文的操作

    2021-11-29 04:41:23
  • 深入了解Python的异常处理机制

    2023-09-03 09:25:41
  • Golang template 包基本原理分析

    2024-04-25 15:18:32
  • PHP策略模式定义与用法示例

    2024-05-13 09:21:04
  • Python实现邮件发送功能的示例详解

    2022-08-18 13:15:43
  • 将Python脚本打包成exe文件

    2021-06-08 12:21:55
  • asp之家 网络编程 m.aspxhome.com