Skip to content

Instantly share code, notes, and snippets.

@horstjens
Last active March 21, 2025 14:30
Show Gist options
  • Save horstjens/d8f870ae9439a9886b05f14bfef605a7 to your computer and use it in GitHub Desktop.
Save horstjens/d8f870ae9439a9886b05f14bfef605a7 to your computer and use it in GitHub Desktop.
chat
import socket
def start_client():
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 12345))
print("Connected to server.")
while True:
# Send a message to the server
message = input("Enter message to server: ")
client_socket.sendall(message.encode('utf-8'))
# Receive a response from the server
response = client_socket.recv(1024).decode('utf-8')
print(f"Received from server: {response}")
if __name__ == "__main__":
start_client()
import FreeSimpleGUI as sg
layout = [
[sg.Text("Chat version 1.0")],
[sg.Multiline(disabled=True,autoscroll=True,
key="history", size=(30,10))],
[sg.Input(size=(20,1), key="command"),
sg.Button("send",bind_return_key=True)],
[sg.Button("quit")],
]
window = sg.Window("chat programm", layout=layout)
while True:
event, values= window.read()
if event in ( "quit", sg.WIN_CLOSED):
break
if event == "send":
old = values["history"]
new = values["command"]
if len(old.strip()) == 0:
window["history"].update(new)
else:
window["history"].update("\n".join((old,new)))
window["command"].update("")
window.close()
import socket
def start_server():
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('localhost', 12345))
server_socket.listen(5)
print("Server is listening on port 12345...")
while True:
# Wait for a client to connect
client_socket, addr = server_socket.accept()
print(f"Connection from {addr} has been established.")
with client_socket:
while True:
# Receive message from client
message = client_socket.recv(1024).decode('utf-8')
if not message:
break
print(f"Received from client: {message}")
# Send a response back to the client
response = input("Enter response to client: ")
client_socket.sendall(response.encode('utf-8'))
if __name__ == "__main__":
start_server()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment