Python两台电脑实现TCP通信的方法示例
作者:AD稳稳 时间:2023-09-07 04:17:34
为了实现Nao机器人与电脑端的TCP通信,于是研究了一下Python实现TCP通信,在网上也看到了很多例子,但大多都是在一台机器上验证。在两台机器上使用,出了一些小故障。
注意:若两台电脑通信出了问题,若能ping通!大部分是防火墙的问题。一开始A做服务器,B做客户端能实现;B做服务器,A做客户端,A就不能连接到B。我换了一台电脑A就能实现通信了。应该是A的防火墙需要设置。但是A的防火墙全关了也不能实现。真是很让人搞不懂。
首先是服务器端代码:
# -*- encoding: utf-8 -*-
import socket
IP = "192.168.1.153" #服务器端可以写"localhost",可以为空字符串"",可以为本机IP地址
port = 40005 #端口号
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP,port))
s.listen(1)
print('listen at port :',port)
conn,addr = s.accept()
print('connected by',addr)
while True:
data = conn.recv(1024)
data = data.decode()#解码
if not data:
break
print('recieved message:',data)
send = raw_input('return:')#python27要写raw_input,python3.X可写input
conn.sendall(send.encode())#再编码发送
conn.close()
s.close()
客户端代码:
# -*- encoding: utf-8 -*-
import socket
import sys
IP = '192.168.1.153' #填写服务器端的IP地址
port = 40005 #端口号必须一致
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((IP,port))
except Exception as e:
print('server not find or not open')
sys.exit()
while True:
trigger = raw_input("send:")
s.sendall(trigger.encode())
data = s.recv(1024)
data = data.decode()
print('recieved:',data)
if trigger.lower() == '1':#发送1结束连接
break
s.close()
来源:https://blog.csdn.net/ADwenwen/article/details/79031085
标签:Python,TCP,通信
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
IE9一个非常牛的“bug”
2010-05-07 12:45:00
Python爬虫中urllib库的进阶学习
2023-12-13 19:31:53
![](https://img.aspxhome.com/file/2023/1/72711_0s.png)
如何用Python来搭建一个简单的推荐系统
2022-07-20 22:17:33
Zabbix实现微信报警功能
2021-10-17 04:40:05
![](https://img.aspxhome.com/file/2023/7/115227_0s.png)
基于.NET平台常用的框架和开源程序整理
2024-06-05 09:26:51
Pytorch pth 格式转ONNX 格式的详细过程
2021-08-29 05:15:28
![](https://img.aspxhome.com/file/2023/4/98874_0s.png)
Sql Server 数据库索引整理语句,自动整理数据库索引
2024-01-14 02:37:25
IE中伪类:hover的使用及BUG
2007-05-11 17:04:00
UTF-8 编码中BOM的检测与删除
2022-06-04 07:44:16
Python 用turtle实现用正方形画圆的例子
2022-08-05 13:56:33
![](https://img.aspxhome.com/file/2023/7/127857_0s.jpg)
Python如何爬取51cto数据并存入MySQL
2024-01-15 02:18:16
![](https://img.aspxhome.com/file/2023/0/90390_0s.png)
bootstrap手风琴制作方法详解
2024-04-10 16:20:11
Golang import 导入包语法及一些特殊用法详解
2024-02-02 08:28:30
在PyTorch中使用标签平滑正则化的问题
2021-12-26 17:46:54
![](https://img.aspxhome.com/file/2023/8/99468_0s.png)
Python调用VBA实现保留原始样式的表格合并方法
2022-10-18 02:40:45
![](https://img.aspxhome.com/file/2023/9/135159_0s.png)
GO语言不固定参数函数与匿名函数的使用
2024-02-17 14:42:17
基于Python实现批量缩放图片(视频)尺寸
2021-03-23 12:21:22
autojs 蚂蚁森林能量自动拾取即给指定好友浇水的实现方法
2024-04-30 10:10:44
![](https://img.aspxhome.com/file/2023/6/130496_0s.gif)
PyQt5每天必学之工具提示功能
2023-03-12 09:22:00
![](https://img.aspxhome.com/file/2023/7/134507_0s.png)
Vue.directive 实现元素scroll逻辑复用
2024-04-30 10:44:11
![](https://img.aspxhome.com/file/2023/1/130061_0s.png)