Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ananyo2012
Last active August 19, 2018 07:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ananyo2012/d0151776fdd9d9ddb9d3ce2e3c368919 to your computer and use it in GitHub Desktop.
Save ananyo2012/d0151776fdd9d9ddb9d3ce2e3c368919 to your computer and use it in GitHub Desktop.
Simple Socket Programming
# A simple Client Program for making requests using socket
import socket
s = socket.socket()
# The socket listens to a specific port
port = 12345
# Connect to the server
s.connect(('127.0.0.1', port))
# Send Request to server
send_data = 'Hello'
s.send(send_data.encode('utf-8'))
# Receive response from server
recv_data = s.recv(1024)
print(recv_data.decode('utf-8'))
# close the connection
s.close()
# A simple server program for listening to requests via socket
import socket
s = socket.socket()
print('Socket Created')
# The socket listens to a specific port
port = 12345
# Bind the socket to a port
# Here the socket listens the request
# coming from any IP address in the network
s.bind(('', port))
print('Socket binded to port %s' % port)
# Put the socket in listening mode
s.listen(5)
print('Socket listening')
while True:
# Establish Connection with the client
c, addr = s.accept()
print('Got Connection from', addr)
# Receive request from client
recv_data = c.recv(1024)
print(recv_data.decode('utf-8'))
# Send a response to client
send_data = 'Thank you for connecting'
c.send(send_data.encode('utf-8'))
# Close the connection
c.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment