Basic Python client socket example Basic Python client socket example python python

Basic Python client socket example


Here is the simplest python socket example.

Server side:

import socketserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)serversocket.bind(('localhost', 8089))serversocket.listen(5) # become a server socket, maximum 5 connectionswhile True:    connection, address = serversocket.accept()    buf = connection.recv(64)    if len(buf) > 0:        print buf        break

Client Side:

import socketclientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)clientsocket.connect(('localhost', 8089))clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates


Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import sockets = socket.socket()host = '111.111.0.11' # needs to be in quoteport = 1247s.connect((host, port))print s.recv(1024)inpt = raw_input('type anything and click enter... ')s.send(inpt)print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import sockets = socket.socket()host = socket.gethostname()port = 1247s.bind((host,port))s.listen(5)while True:    c, addr = s.accept()    print("Connection accepted from " + repr(addr[1]))    c.send("Server approved connection\n")    print repr(addr[1]) + ": " + c.recv(1026)    c.close()

Run the server program and then the client one.


It's trying to connect to the computer it's running on on port 5000, but the connection is being refused. Are you sure you have a server running?

If not, you can use netcat for testing:

nc -l -k -p 5000

Some implementations may require you to omit the -p flag.