Simple Socket Programming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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