简体   繁体   中英

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

I have a python script which creates a variable 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() . Your server part currently doesn't listen to a socket and doesn't accept connections. Also the server part should recv data from the socket returned by accept , but not the one that you're listening to.
  • You need to ensure that heading variable is a string. Otherwise you might want to use JSON or pickle module to serialize your objects.

I'd suggest you to read the socket module examples at official Python documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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