Skip to content

Instantly share code, notes, and snippets.

@adrianjost
Last active July 23, 2020 22:57
Show Gist options
  • Save adrianjost/7673ca97c15f5b9e05c3af94b660b6c4 to your computer and use it in GitHub Desktop.
Save adrianjost/7673ca97c15f5b9e05c3af94b660b6c4 to your computer and use it in GitHub Desktop.
Python 3 TCP float (double) adder
import socket
import sys
""" based on https://pymotw.com/3/socket/tcp.html
modified by Adrian Jost"""
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('127.0.0.1', 1111)
print('starting up on {} port {}'.format(*server_address))
sock.bind(server_address)
# Listen for one incoming connections
sock.listen(1)
def parse(data):
try:
items = data.decode().split(";")
return str(float(items[0]) + float(items[1]))
except:
return False
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
print('connection from', client_address)
while True:
# Receive the data and try to calculate
data = connection.recv(1024)
print('received {!r}'.format(data))
if data:
if(parse(data)):
print('sending data back to the client', parse(data))
connection.sendall(parse(data).encode())
else:
print('no data from', client_address)
break
finally:
# Clean up the connection
connection.close()
@adrianjost
Copy link
Author

It was just a simple homework. You won't find clean code or detailed explenations here. I definetly recommend google here ;)

@adrianjost
Copy link
Author

test it with this code

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the port where the server is listening
server_address = ('127.0.0.1', 1111)
print('connecting to {} port {}'.format(*server_address))
sock.connect(server_address)

try:

    # Send data
    message = b'12;13;'
    print('sending {!r}'.format(message))
    sock.sendall(message)

    data = sock.recv(16)
    print('received {!r}'.format(data))

finally:
    print('closing socket')
    sock.close()

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