Skip to content

Instantly share code, notes, and snippets.

@hedinasr
Last active November 15, 2016 10:34
Show Gist options
  • Save hedinasr/21137713887f10f5b357303a6aae3832 to your computer and use it in GitHub Desktop.
Save hedinasr/21137713887f10f5b357303a6aae3832 to your computer and use it in GitHub Desktop.
Client/Server application using Python Socket API
# -*- coding: utf-8 -*-
import socket
from utils import readlines
"""
Client.
"""
# Création de la socket TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# On se connecte sur le port 8080
server_address = ('localhost', 8084)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# Send data
message = b'Bonjour\n'
print('sending "%s"' % message)
sock.sendall(message)
# Receive data
for line in readlines(sock):
print(line)
if 'Au revoir' in line:
break
finally:
# Close the connection
sock.close()
# -*- coding: utf-8 -*-
import socket
from utils import readlines
"""
Un simple client HTTP.
"""
# Création de la socket TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# On se connecte sur le port 80 de google
server_address = ('www.google.com', 80)
print('connecting to %s port %s' % server_address)
sock.connect(server_address)
try:
# Send HTTP request
request = input('> ')
print('sending "%s"' % request)
sock.sendall((request + '\n\n').encode())
# Receive the response
for line in readlines(sock, delim='\r\n'):
print(line)
if line == '\r': # caractère de fin de réponse HTTP
break
finally:
# Close the connection
sock.close()
# -*- coding: utf-8 -*-
import socket
from utils import readlines
"""
Serveur qui renvoi (60 fois) l'heure au client.
"""
# Création de la socket TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind de la socket au port 8080
server_address = ('localhost', 8084)
print('listen on %s port %s' % server_address)
sock.bind(server_address)
# Attente des connexions
sock.listen(1)
while True:
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
# Receive data
for line in readlines(connection):
print('receive "%s"' % line)
if 'Bonjour' in line:
# Envoi 60 fois l'heure au client
for i in range(60):
print('sending data (%s)' % i)
connection.sendall(b'Test\n')
# Say goodbye
connection.sendall(b'Au revoir\n')
break
finally:
# Close the connection
connection.close()
# -*- coding: utf-8 -*-
"""
Some useful function.
"""
def readlines(sock, buffer_size=2048, delim='\n'):
"""
Read data from socket until connection is closed,
and supply a generator interface.
"""
buf = ''
data = True
while data:
data = sock.recv(buffer_size)
buf += data.decode()
while buf.find(delim) != -1:
line, buf = buf.split('\n', 1)
yield line
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment