-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
47 lines (40 loc) · 1.47 KB
/
Copy pathserver.py
File metadata and controls
47 lines (40 loc) · 1.47 KB
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
37
38
39
40
41
42
43
44
45
46
47
from socket import *
from threading import Thread
# Server IP address
IP = '127.0.0.1'
# Port number
PORT = 50000
# Define buffer size for receiving data
BUFLEN = 1024
# Create a listening socket
listenSocket = socket(AF_INET, SOCK_STREAM)
# Bind socket to address and port
listenSocket.bind((IP, PORT))
# Set socket to listening mode
listenSocket.listen(8)
print(f'Server started successfully, listening on port {PORT}...')
# Accept two clients
clientSocket1, addr1 = listenSocket.accept()
print('Accepted connection from:', addr1)
clientSocket2, addr2 = listenSocket.accept()
print('Accepted connection from:', addr2)
def threadFunc(clientSocket, targetSocket):
while True:
# Attempt to read incoming message
received = clientSocket.recv(BUFLEN)
# If an empty message is received, it indicates the other side has closed the connection
if received.decode() == 'exit':
targetSocket.send('【System Message】: The other party has exited, conversation ended'.encode())
break
else:
message = received.decode()
print(f'Received message: {message}')
targetSocket.send(message.encode())
clientSocket.close()
# Create threads for bidirectional communication
thread1 = Thread(target=threadFunc, args=(clientSocket1, clientSocket2))
thread2 = Thread(target=threadFunc, args=(clientSocket2, clientSocket1))
thread1.start()
thread2.start()
# Close the listening socket
listenSocket.close()