Skip to content

Instantly share code, notes, and snippets.

@jamilatta
Last active December 29, 2015 02:59
Show Gist options
  • Save jamilatta/7603968 to your computer and use it in GitHub Desktop.
Save jamilatta/7603968 to your computer and use it in GitHub Desktop.
Example of client and server socket in python.
#!/usr/bin/python
import socket
import os, os.path
print "Connecting..."
if os.path.exists('./example.sock'):
client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
client.connect('./example.sock')
print "Ready"
print "Ctrl-C to quit."
print "Sending 'DONE' shuts down the server and quits"
while True:
try:
x = raw_input('>')
if x != "":
print "SEND: ", x
client.send(x)
if x == "DONE":
print "Shutting down."
break
except KeyboardInterrupt, k:
print "Shutting down"
client.close()
else:
print "Couldn`t Connect!"
print "Done"
#!/usr/bin/python
import socket
import os, os.path
#Set the file name
sockfile = "./example.sock"
#Verify if exists the sock file
if os.path.exists(sockfile):
os.remove(sockfile)
#Print start msg
print "Start socket server, socket file: " + sockfile
#AF_UNIX and SOCK_STREAM are constants represent the protocol and socket type respectively
#http://docs.python.org/2/library/socket.html#socket.AF_UNIX
#http://docs.python.org/2/library/socket.html#socket.SOCK_STREAM
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
#Bind to the socket file
#http://docs.python.org/2/library/socket.html#socket.socket.bind
server.bind(sockfile)
#Listen for connections, the param 5 specifies the maximum number of queued connections
#http://docs.python.org/2/library/socket.html#socket.socket.listen
server.listen(5)
print "Listening..."
while True:
#Accept a connection
#http://docs.python.org/2/library/socket.html#socket.socket.accept
#conn = is a new socket object usable to send and receive data on the connection
#addr = is the address bound to the socket *on the other* end of connection
conn, addr = server.accept()
print "new connection..."
while True:
#Receive data from socket
#Return a string represent the data received
#http://docs.python.org/2/library/socket.html#socket.socket.recv
data = conn.recv(1024)
if not data:
break;
else:
print "-" * 20
print data
if "DONE" == data:
break;
print "-" * 20
print "Shutting down..."
server.close()
os.remove(sockfile)
print "Finish server socket."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment