Home › Forums › Python Programming › socket programming in python ?
- This topic has 0 replies, 1 voice, and was last updated 10 years, 4 months ago by Humble.
Viewing 1 post (of 1 total)
-
AuthorPosts
-
HumbleKeymaster
Almost everyone know how socket programming works .. Its no different in python. The same pattern follows..
If you are writing a server side program. It should have:
1) Create a socket object
2) Bind it with the hostname and port
3) Start istening for the incoming connection
4) Sending data to client
5) Close the socketClient side:
1) Create socket object
2) Connect to the server
3) Receive reply from the server..
4) close the socket[1]
A quick demonstration of the above can be shown like :
#!/usr/bin/python #You need to import socket module import socket import sys #Create a socket object .. sockObj = socket.socket() # You can get IP address of any host by using below method remote = socket.gethostbyname("www.yahoo.com") # If you want to get your hostname , use below local = socket.gethostname() # define a port to work with myport= 54321 print ("Remote server :%s , Local :%s") %(remote, local) try: # Binding the socket , you can use "local", remote #variables stored above as first argument for the bind call sockObj.bind(('127.0.0.1',myport)) # Let it listen! sockObj.listen(5) except Exception as e: print "Error in operation :({0}): ({1})".format(e.errno, e.strerror) while True: # Accept client connection client, addr = sockObj.accept() print 'Got connection from', addr # sending data to client c.send('You are welcome and Thank you for connecting') # Then closing the socket c.close() Client Program
#!/usr/bin/python import socket # Create a socket object clientSocket = socket.socket() host = socket.gethostname() port = 54321 #Connecting to server program clientSocket.connect(("127.0.0.1", port)) #Receiving date from the server print clientSocket.recv(1024) #Close it clientSocket.close Now, try to execute the server and client program: In one terminal execute server.py and let it listen In other terminal execute client program : [hchiramm@humbles-lap sql-back]$ ./client.py You are welcome and Thank you for connecting Let me know if you need further explanation..
-
AuthorPosts
Viewing 1 post (of 1 total)