Skip to content

Instantly share code, notes, and snippets.

@damianmoore
Created January 23, 2019 07:21
Show Gist options
  • Save damianmoore/503c1a0b2b95bb206ad8ce511c586221 to your computer and use it in GitHub Desktop.
Save damianmoore/503c1a0b2b95bb206ad8ce511c586221 to your computer and use it in GitHub Desktop.
Python TCP client
# https://www.techbeamers.com/python-tutorial-write-tcp-server/
import socket
host_ip, server_port = "127.0.0.1", 9999
data = "Hello how are you?\n"
# Initialize a TCP client socket using SOCK_STREAM
tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Establish connection to TCP server and exchange data
tcp_client.connect((host_ip, server_port))
tcp_client.sendall(data.encode())
# Read data from the TCP server and close the connection
received = tcp_client.recv(1024)
finally:
tcp_client.close()
print("Bytes Sent: {}".format(data))
print("Bytes Received: {}".format(received.decode()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment