[python][network] simplest networking

I just want python to send a line of text to the other script on the other computer

they are on the same network,


just a server script listening for

a client script sending one line of text,

is it possible?
Who is Participating?
peprConnect With a Mentor Commented:
If you are allowed, see the question http:#21995292 and the answers. If you cannot search for the answers, here are copies of my answers...

1) Focus on the built-in module socket (Python doc "7.2 socket -- Low-level networking interface"). See the examples:


They are a bit old and could be written aestetically better, but they show the principle. (Add the line UDPSock.sendto('', addr) before the break to finish the server when sending empty line.)

Later, you may get info and inspiration in the standard module SocketServer Python doc ("11.16 SocketServer -- A framework for network servers")

Use the snippets below, store them in separate files -- one for the server, one for the client. The UDP is the simplest form of usage of the IP protocol. See http://en.wikipedia.org/wiki/User_Datagram_Protocol. More reliable transfer can be done via TCP (see http://en.wikipedia.org/wiki/Transmission_Control_Protocol).
# Server program
import socket
# Set the socket parameters
addr = ('', 33333)  # host, port
# Create socket and bind to address
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Receive messages
while True:
    data, addr = UDPSock.recvfrom(1024)
    if data == 'stop':
        print 'Client wants me to stop.'
        print "From addr: '%s', msg: '%s'" % (addr[0], data)
# Close socket
print 'Server stopped.'
# Client program
import socket
#addr = ('localhost', 33333)                                # localhost, port
#addr = ('', 33333)                                # localhost explicitly
#addr = ('xyz', 33333)                                      # explicit computer
#addr = ('<broadcast>', 33333)                              # broadcast address
addr = ('', 33333)                          # broadcast address explicitly
UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Create socket
print 'Enter your message:'
print '- Empty message to stop this client.'
print '- "stop" to stop all servers.'
# Almost infinite loop... ;)
while True:
    data = raw_input('>> ')
    if len(data) == 0:
        if UDPSock.sendto(data, addr):
            print "Sending message '%s'..." % data
UDPSock.close()             # Close socket
print 'Client stopped.'

Open in new window

ramromconsultant Commented:
Yes - see the socket module
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.