Skip to content

Instantly share code, notes, and snippets.

@wjstk16
Created July 30, 2024 05:06
Show Gist options
  • Save wjstk16/d98064f5c565f532cf8f17e8880102b7 to your computer and use it in GitHub Desktop.
Save wjstk16/d98064f5c565f532cf8f17e8880102b7 to your computer and use it in GitHub Desktop.
import socket
import sys
import time
import logging
# Set up logging to file and console
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("tcp.log"), logging.StreamHandler()])
def connect_and_communicate(server_ip, client_ip, port):
while True:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as cl_socket:
cl_socket.bind((client_ip, 0))
logging.info(f"Trying to connect to {server_ip}:{port}")
cl_socket.connect((server_ip, port))
logging.info(f"Connected to {server_ip}:{port}")
val = 1
while True:
try:
# Send data
logging.info(f"Sending value: {val}")
cl_socket.sendall(val.to_bytes(4, 'little'))
logging.info(f"Sent value: {val}")
rval = int.from_bytes(cl_socket.recv(4), 'little')
logging.info(f"Received value: {rval}")
logging.info(f"PP {val} -> {rval}")
val += 1
time.sleep(1)
except Exception as e:
logging.error(f"Communication error: {e}")
break
except Exception as e:
logging.error(f"Connection failed: {e}")
logging.info("Reconnecting...")
time.sleep(2)
if __name__ == "__main__":
if len(sys.argv) != 4:
logging.error("Usage: python client.py <server_ip> <client_ip> <port>")
sys.exit(1)
connect_and_communicate(sys.argv[1], sys.argv[2], int(sys.argv[3]))
import socket
import sys
import logging
# Set up logging to file and console
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.FileHandler("tcp.log"), logging.StreamHandler()])
def serve_new_conn(conn, addr):
logging.info(f"New connection from {addr}")
while True:
try:
data = conn.recv(1024)
if not data:
break
conn.sendall(data)
except Exception as e:
logging.error(f"Error: {e}")
break
logging.info("Connection closed")
def main_srv(ip, port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv_socket:
srv_socket.bind((ip, port))
srv_socket.listen()
logging.info(f"Binding to {ip}:{port}")
logging.info("Waiting for connections")
while True:
conn, addr = srv_socket.accept()
serve_new_conn(conn, addr)
conn.close()
if __name__ == "__main__":
if len(sys.argv) != 3:
logging.error("Usage: python server.py <ip> <port>")
sys.exit(1)
server_ip = sys.argv[1]
server_port = int(sys.argv[2])
main_srv(server_ip, server_port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment