Skip to content

Instantly share code, notes, and snippets.

@alxwrd
Created August 23, 2017 09:58
Show Gist options
  • Save alxwrd/b9133476e2f11263e594d8c29256859a to your computer and use it in GitHub Desktop.
Save alxwrd/b9133476e2f11263e594d8c29256859a to your computer and use it in GitHub Desktop.
Socket server-client example
from __future__ import print_function
import socket
try:
input = raw_input
except NameError:
pass
host = socket.gethostname()
port = 12345
while True:
req = input("Request to send: ")
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
s.connect((host, port))
try:
s.sendall(bytes(req, "ascii"))
except TypeError:
s.sendall(req)
data = s.recv(1024)
s.close()
print('Received', repr(data))
from __future__ import print_function
import socket
import time
host = ""
port = 12345
s = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
print("Listening on port: {}".format(port))
conn, addr = s.accept()
print("Connected by", addr)
# Receive all data
while True:
data = conn.recv(1024)
print("Recevied some data: {}".format(data))
print("It was of type: {}".format(type(data)))
break
print("Checking data to form response")
# Check the data and prepare the response
if data == "TIME" or data == b"TIME":
time_str = (time.ctime(time.time()) + "\r\n").encode('ascii')
print("Got a TIME request, sending: {}".format(time_str))
return_data = time_str
else:
print("Got a {} request, unknown.".format(data))
return_data = "Unknown request"
# Send the result back to the client
try:
conn.sendall(bytes(return_data, "ascii"))
except TypeError:
conn.sendall(return_data)
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment