简体   繁体   English

如何连接2个节点并使用python套接字通过它们发送数据?

[英]How can I connect 2 nodes and send data over them using python sockets?

I have a python script which creates a variable heading . 我有一个Python脚本,它创建一个可变的heading I want to transmit this heading to another node in a wireless ad-hoc network. 我想将此标题传输到无线自组织网络中的另一个节点。

I have looked at a lot of tutorials and examples but I don't quite understand which end is which for the sockets. 我看了很多教程和示例,但是我不太了解套接字的哪一端。

I think on the node I have created the variable I would have code something like this: 我认为在节点上创建变量后,我将得到如下代码:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((ipv4_address, 50086))
s.send(heading)

And on the receiving end I would want something listening on the same port waiting for the heading to arrive: 在接收端,我希望在同一端口上监听某些内容,以等待航向到达:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((ipv4_address, 50086))
while 1:
    data = client_socket.recv(512)

I'm not sure if I am getting the connect and bind the right way around? 我不确定是否可以正确连接并绑定连接?

  • The server part must perform the sequence socket() , bind() , listen() , accept() . 服务器部分必须执行序列socket()bind()listen()accept() Your server part currently doesn't listen to a socket and doesn't accept connections. 您的服务器部分当前不listen套接字,也不accept连接。 Also the server part should recv data from the socket returned by accept , but not the one that you're listening to. 服务器部分也应该从accept返回的套接字中recv数据,而不是正在侦听的数据。
  • You need to ensure that heading variable is a string. 您需要确保heading变量是一个字符串。 Otherwise you might want to use JSON or pickle module to serialize your objects. 否则,您可能想使用JSONpickle模块来序列化对象。

I'd suggest you to read the socket module examples at official Python documentation. 我建议您阅读官方Python文档中的socket module examples

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM