Python一个简单的通信程序(客户端 服务器)
作者:Dai___ 时间:2023-09-09 11:09:39
功能是从客户端向服务发送一个字符串, 服务器收到后将字符串重新发送给客户端,同时,在连接建立之后,服务器可以向客户端发送任意多的字符串
客户端:
10.248.27.23是我电脑的IP
import socket, sys
host = '10.248.27.23'
# host = raw_input("Plz imput destination IP:")
# data = raw_input("Plz imput what you want to submit:")
port = 51423
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((host, port))
except socket.gaierror, e:
print "Address-related error connecting to server: %s" %e
sys.exit(1)
except socket.error, e:
print "Connection error: %s" %e
sys.exit(1)
data = raw_input("Plz imput what you want to submit:")
s.send(data)
s.shutdown(1)
print "Submit Complete"
while 1:
buf = s.recv(1024)
sys.stdout.write(buf)
服务器:
import socket, traceback
host = ''
port = 51423
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 "done"
while 1:
#when connect error happen, skip the error
try:
ClientSock, ClientAddr = s.accept()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
continue
#Get informaion form client and reply
try:
print "Get connect from ", ClientSock.getpeername()
data = ClientSock.recv(1024)
print "The information we get is %s" % str(data)
ClientSock.sendall("I`ve got the information: ")
ClientSock.sendall(data)
while 1:
str = raw_input("What you want to say:")
ClientSock.sendall(str)
ClientSock.sendall('\n')
except (KeyboardInterrupt ,SystemError):
raise
except:
traceback.print_exc()
#Clocs socket
try:
ClientSock.close()
except KeyboardInterrupt:
raise
except:
traceback.print_exc()
来源:https://blog.csdn.net/rebelqsp/article/details/22183981
标签:python,通信程序,客户端,服务器
0
投稿
猜你喜欢
asp如何更好地保护我的网页?
2009-11-22 19:29:00
Python pyinotify模块实现对文档的实时监控功能方法
2023-04-15 08:13:52
Pycharm中配置Anaconda解释器的完整步骤
2021-12-16 16:37:38
python基础详解之if循环语句
2022-04-17 02:14:09
Pytorch实现神经网络的分类方式
2021-02-26 05:20:47
Python爬虫解析网页的4种方式实例及原理解析
2022-11-03 03:11:23
在HTML中,常见的URL有多种表示方式:
2009-07-28 12:18:00
SqlServer提示“列前缀tempdb.无效: 未指定表名”问题解决方案
2024-01-14 04:39:41
python实现视频读取和转化图片
2023-09-25 08:23:22
vue新玩法VueUse工具库具体用法@vueuse/core详解
2023-07-02 16:55:44
vue.js 实现点击展开收起动画效果
2024-05-29 22:47:44
go time.After优化后性能提升34%内存减少67%
2024-05-05 09:33:34
python制作抖音代码舞
2021-09-05 21:51:00
MySQL中进行跨库查询的方法示例
2024-01-26 10:27:39
Pytorch模型迁移和迁移学习,导入部分模型参数的操作
2021-08-05 09:18:16
带有定位当前位置的百度地图前端web api实例代码
2024-05-08 10:11:56
python 对任意数据和曲线进行拟合并求出函数表达式的三种解决方案
2021-10-02 12:40:16
python生成器用法实例详解
2023-01-24 12:46:58
OpenCV+python实现膨胀和腐蚀的示例
2021-06-12 10:35:00
Python实现将mp3音频格式转换为wav格式
2023-09-18 15:50:02