Skip to content

Commit e2ddeb5

Browse files
committed
base code
1 parent d284631 commit e2ddeb5

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

client.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import socket
2+
import threading
3+
4+
# Choose a username
5+
username = input("Enter your username: ")
6+
7+
# Client setup
8+
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
9+
client.connect(('localhost', 12345))
10+
11+
# Listening to server and sending messages
12+
def receive_messages():
13+
while True:
14+
try:
15+
message = client.recv(1024).decode('utf-8')
16+
if message == 'USERNAME':
17+
client.send(username.encode('utf-8'))
18+
else:
19+
print(message)
20+
except:
21+
print('An error occurred!')
22+
client.close()
23+
break
24+
25+
def write_messages():
26+
while True:
27+
message = f'{username}: {input("")}'
28+
client.send(message.encode('utf-8'))
29+
30+
receive_thread = threading.Thread(target=receive_messages)
31+
receive_thread.start()
32+
33+
write_thread = threading.Thread(target=write_messages)
34+
write_thread.start()

server.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import socket
2+
import threading
3+
4+
# Server setup
5+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
6+
server.bind(('localhost', 12345))
7+
server.listen()
8+
9+
clients = []
10+
usernames = []
11+
12+
# Broadcast messages to all clients
13+
def broadcast(message):
14+
for client in clients:
15+
client.send(message)
16+
17+
# Handle messages from clients
18+
def handle_client(client):
19+
while True:
20+
try:
21+
message = client.recv(1024)
22+
broadcast(message)
23+
except:
24+
index = clients.index(client)
25+
clients.remove(client)
26+
client.close()
27+
username = usernames[index]
28+
broadcast(f'{username} has left the chat!'.encode('utf-8'))
29+
usernames.remove(username)
30+
break
31+
32+
# Receive connections from clients
33+
def receive_connections():
34+
while True:
35+
client, address = server.accept()
36+
print(f'Connected with {str(address)}')
37+
38+
client.send('USERNAME'.encode('utf-8'))
39+
username = client.recv(1024).decode('utf-8')
40+
usernames.append(username)
41+
clients.append(client)
42+
43+
print(f'Username of the client is {username}')
44+
broadcast(f'{username} has joined the chat!'.encode('utf-8'))
45+
client.send('Connected to the server!'.encode('utf-8'))
46+
47+
thread = threading.Thread(target=handle_client, args=(client,))
48+
thread.start()
49+
50+
print('Server is listening...')
51+
receive_connections()

0 commit comments

Comments
 (0)