-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path001-TCP-chat-server.py
More file actions
36 lines (28 loc) · 973 Bytes
/
001-TCP-chat-server.py
File metadata and controls
36 lines (28 loc) · 973 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import socket
import threading
# Set address and port
server_address = ('localhost', 10000)
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(server_address)
sock.listen()
def handle_client(conn, address):
# Receive data from the client
data = conn.recv(4096)
data = data.decode()
print(f'Received {data} from {address}')
def handle_incoming_connections():
while True:
conn, address = sock.accept()
print(f'Accepted connection from {address}')
# Start a new thread to handle the client
thread = threading.Thread(target=handle_client, args=(conn, address))
thread.start()
# Start a new thread to handle incoming connections
thread = threading.Thread(target=handle_incoming_connections)
thread.start()
# Run the server eternal
while True:
message = input('Enter a message to send: ')
for conn, address in connected_clients:
conn.send(message.encode())