Mega Code Archive

 
Categories / Python Tutorial / Network
 

A server that will receive a connection from a client, send a string to the client, and close the connection

import socket HOST = "127.0.0.1" PORT = 5000 counter = 0 mySocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) try:    mySocket.bind( ( HOST, PORT ) )  except socket.error:    print "Call to bind failed" while 1:    print "Waiting for connection"    mySocket.listen( 1 )    connection, address = mySocket.accept()    counter += 1    print "Connection", counter, "received from:", address[ 0 ]    connection.send( "SERVER Connection successful" )    clientMessage = connection.recv( 1024 )    while clientMessage != "CLIENT TERMINATE":       if not clientMessage:          break       print clientMessage       serverMessage = "message"        connection.send( "SERVER " + serverMessage )       clientMessage = connection.recv( 1024 )    print "Connection terminated"    connection.close()