Skip to content

Instantly share code, notes, and snippets.

@bend
Created April 20, 2018 10:18
Show Gist options
  • Save bend/0a7c900a6ea17c7f6cc302d86c6539d5 to your computer and use it in GitHub Desktop.
Save bend/0a7c900a6ea17c7f6cc302d86c6539d5 to your computer and use it in GitHub Desktop.
Simple ping pong client server
#!/usr/bin/env python
import socket
from socket import error as socket_error
import sys
import time
MSGLEN=4
SLEEP_DELAY=1
class PingPongClientServer:
def __init__(self, host, port):
self.host = host
self.port = port
def receive(self, sock):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return b''.join(chunks)
def send(self, sock, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
class PingPongServer(PingPongClientServer):
def __init__(self, host, port):
PingPongClientServer.__init__(self, host, port)
def listen(self):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((self.host, self.port))
print("server listening on ", self.port)
server.listen(5)
while 1:
try:
(clientsocket, address) = server.accept()
while 1:
chunk = self.receive(clientsocket)
print("server received " , chunk)
if chunk == "ping":
self.send(clientsocket, "pong")
except RuntimeError:
print("Connection broken with client")
class PingPongClient(PingPongClientServer):
def __init__(self, host, port):
PingPongClientServer.__init__(self, host, port)
def connect(self):
while 1:
try:
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((self.host, self.port))
while 1:
self.send(client, "ping")
data = self.receive(client)
print("client received" ,data)
time.sleep(SLEEP_DELAY)
except (RuntimeError, socket_error):
print("Connection closed with server")
if __name__ == "__main__":
if(sys.argv[1] == "server"):
server = PingPongServer(sys.argv[2], int(sys.argv[3]))
server.listen()
else:
client = PingPongClient(sys.argv[2], int(sys.argv[3]))
client.connect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment