Send data from sender to receiver in python where each run on separate machines
I am looking to learn if you know of any python libraries or methodologies that would allow me to do the following.
I am looking to run two python scripts, sender & receiver. I would like each to run on separate machines in Python. I want the sender to pass a data string to receiver over the internet.
Any idea on how I can do this?
Much appreciated!
If you want to accomplish this task you need to take a look at the python socket.py module (https://docs.python.org/3/library/socket.html).
An example for a sender script from (https://www.geeksforgeeks.org/socket-programming-python/):
# first of all import the socket library
import socket
# next create a socket object
s = socket.socket()
print ("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
s.bind(('', port))
print ("socket binded to %s" %(port))
# put the socket into listening mode
s.listen(5)
print ("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
while True:
# Establish connection with client.
c, addr = s.accept()
print ('Got connection from', addr )
# send a thank you message to the client. encoding to send byte type.
c.send('Thank you for connecting'.encode())
# Close the connection with the client
c.close()
# Breaking once connection closed
break
An example for a reciever script that can be run on the same machine or another machine:
# Import socket module
import socket
# Create a socket object
s = socket.socket()
# Define the port on which you want to connect
port = 12345
# connect to the server on local computer
s.connect(('127.0.0.1', port))
# receive data from the server and decoding to get the string.
print (s.recv(1024).decode())
# close the connection
s.close()
Here in the two examples the two scripts were running on the same machine but you can change that.
This document can be helpful too (https://docs.python.org/3/howto/sockets.html)