Skip to content

Instantly share code, notes, and snippets.

@davidlares
Last active September 2, 2019 01:51
Show Gist options
  • Save davidlares/5bdc0e9a3d592cfe16b911ce42e2470c to your computer and use it in GitHub Desktop.
Save davidlares/5bdc0e9a3d592cfe16b911ce42e2470c to your computer and use it in GitHub Desktop.
Client-Server programming using sockets (Python built-in library)
#!/usr/bin/python
# socket network module (methods and APIs)
import socket
import sys
# creating a TCP Socket -> listening to an specific port
# AF_INET -> address family , SOCK_STREAM -> Kind of socket (required)
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# connection to a socket (Main difference between listening and bounding) = From Client.
tcpSocket.connect((sys.argv[1], 8000)) # param IP received
# continuing reading
while True:
# reading input
userInput = raw_input("Please enter a string: ")
# sending information
tcpSocket.send(userInput)
print tcpSocket.recv(2048)
# closing socket
tcpSocket.close()
#!/usr/bin/python
# socket network module (methods and APIs)
import socket
# creating a TCP Socket -> listening to an specific port
# AF_INET -> address family, SOCK_STREAM -> Kind of socket required
tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this makes the socket reusable
tcpSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# binding IP and Port
tcpSocket.bind(("0.0.0.0", 8000))
# listening on the bound port and IP for client
# concurrent clients
tcpSocket.listen(2)
# start accepting clients
print "Receiving clients"
(client, (ip,sock)) = tcpSocket.accept() # returns a tuple (client side socket) -> one per client, and client IP and PORT
print client # renote client object
print "Received connection from: ", ip # remote client IP
print "Starting ECHO output ..."
# sending to the client
data = "david"
while len(data):
# whatever the client sends, receiving data from the client - 2048 - buffer
data = client.recv(2048)
print "Client Sent: ", data
client.send(data)
print "Closing Connection..."
client.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment