inital commit

This commit is contained in:
2026-03-24 13:52:13 -04:00
commit 03931fddfe
3 changed files with 102 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
import socket
import threading
# function for messages from server
def receive_server(s):
while True:
# the try block makes it not error when it dissconnects
try:
message = s.recv(1024).decode()
if not message:
print("\nServer closed the connection")
break
print(f"\nServer: {message}")
except:
print("\nDisconnected from server.")
break
#create socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#connect to server
client_socket.connect(("localhost", 12345))
print("Connected to server.")
print("Type 'quit' to exit.")
# starts the recieving thread
receive_thread = threading.Thread(target=receive_server, args=(client_socket,))
receive_thread.start()
# loop for sending the messages
while True:
msg = input()
if msg.lower() == 'quit':
break
client_socket.send(msg.encode())
#close connection
client_socket.close()
+7
View File
@@ -0,0 +1,7 @@
How to run code:
First run server.py in the terminal
Next run client.py on a seperate terminal
Now that you have established a connection you can send messages to eachother until you want to stop
To end the connection type 'quit' on either side to end the connction
+53
View File
@@ -0,0 +1,53 @@
import socket
import threading
# this function recieves the thread
def receive_messages(connection):
while True:
# the try block makes it not error when it dissconnects
try:
# this waits for the message from client
message = connection.recv(1024).decode()
if not message:
# if the client closes the connection its empty
print("\nClient Disconnected")
break
except:
print("\nConnection closed.")
break
# the 'flush' fixes the outputs overriding each other in terminal
print(f"\nClient: {message}")
# the function for
def send_messages(connection):
while True:
# this waits for you to type
message = input()
if message.lower() == 'quit':
connection.close()
break
connection.send(message.encode())
#create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#give socket port and address
server_socket.bind(("localhost", 12345))
#listen for connections
server_socket.listen()
print("Server is waiting for connection...")
#accept connection
conn, addr = server_socket.accept()
print("Connected to:", addr)
# the two threads for the inputs
receive_thread = threading.Thread(target=receive_messages, args=(conn,))
send_thread = threading.Thread(target=send_messages, args=(conn,))
# starts the process
receive_thread.start()
send_thread.start()