Skip to content

Instantly share code, notes, and snippets.

@grihabor
Last active October 5, 2018 13:56
Show Gist options
  • Save grihabor/c5bb1ce28708bfa0198c77157d699d86 to your computer and use it in GitHub Desktop.
Save grihabor/c5bb1ce28708bfa0198c77157d699d86 to your computer and use it in GitHub Desktop.
Simple python client-server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("localhost", 50010))
msg_to_send = 'Hello world!'
bytes_to_send = msg_to_send.encode('utf-8')
print('Send to the server:', msg_to_send)
s.send(bytes_to_send)
bytes_from_server = s.recv(1024)
print('Bytes from server:', bytes_from_server)
msg_from_server = bytes_from_server.decode('utf-8')
print('Message from server:', msg_from_server)
import socketserver
class Handler(socketserver.BaseRequestHandler):
def handle(self):
bytes_from_client = self.request.recv(1024)
print('Bytes from client:', bytes_from_client)
msg = bytes_from_client.decode('utf-8')
print('Message from client:', msg)
self.request.send('OK'.encode('utf-8'))
if __name__ == '__main__':
with socketserver.TCPServer(('localhost', 50010), Handler) as server:
server.serve_forever()
@grihabor
Copy link
Author

grihabor commented Oct 5, 2018

Run a server: python3 server.py
Run a client: python3 client.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment