-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtestetcp04.py
133 lines (110 loc) · 4.79 KB
/
testetcp04.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import socket
import threading
import time
import json
receiver_id = 0
conversation_id = 0
def receive_messages(sock, client_id):
while True:
try:
message = sock.recv(1024).decode('utf-8')
if message:
# Deserialize the JSON message
data = json.loads(message)
print(f"\n{data['Content']}")
if 'SenderId' in data and data['SenderId'] == 0:
print("Server: " + data['Content'])
elif 'SenderId' in data and data['SenderId'] != 0:
acknoledgment(sock, data, client_id)
except Exception as e:
print("An error occurred:", e)
break
def send_messages(sock, client_id):
global conversation_id
global receiver_id
while True:
message = input()
if message.lower() == 'exit':
break
if message.lower() == '/exit':
conversation_id = 0
receiver_id = 0
if message:
# Create a message dictionary
msg_dict = {
"SenderId": client_id, # Use the assigned client ID
"ReceiverId": receiver_id, # This can be set when connecting to another client
"Content": message,
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"ConversationId": conversation_id
}
# Serialize the dictionary to JSON
json_message = json.dumps(msg_dict)
sock.send(json_message.encode('utf-8'))
def send_heartbeat(sock, client_id):
while True:
time.sleep(3) # Send a heartbeat every 5 seconds
try:
# Create a message dictionary
msg_dict = {
"SenderId": client_id, # Use the assigned client ID
"ReceiverId": receiver_id, # This can be set when connecting to another client
"Content": "heartbeat",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"ConversationId": conversation_id
}
# Serialize the dictionary to JSON
json_message = json.dumps(msg_dict)
sock.send(json_message.encode('utf-8'))
except:
break # Stop if the connection is closed
def acknoledgment(sock, data, client_id):
global conversation_id
global receiver_id
if data['SenderId'] != conversation_id:
conversation_id = data['SenderId']
receiver_id = data["SenderId"]
msg_dict = {
"SenderId": client_id, # Use the assigned client ID
"ReceiverId": receiver_id, # This can be set when connecting to another client
"Content": "/acknoledgment",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"ConversationId": conversation_id
}
# Serialize the dictionary to JSON
json_message = json.dumps(msg_dict)
sock.send(json_message.encode('utf-8'))
else:
msg_dict = {
"SenderId": client_id, # Use the assigned client ID
"ReceiverId": receiver_id, # This can be set when connecting to another client
"Content": "/acknoledgment",
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"ConversationId": conversation_id
}
# Serialize the dictionary to JSON
json_message = json.dumps(msg_dict)
sock.send(json_message.encode('utf-8'))
def main():
server_ip = "127.0.0.1" # Change this to the server's IP if needed
server_port = 8888
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((server_ip, server_port))
# Start the thread to receive messages
# Keep the main thread open to send messages
client_id = None
while client_id is None:
# Receive the assigned client ID
message = client_socket.recv(1024).decode('utf-8')
if message:
data = json.loads(message)
if 'Content' in data and 'Your assigned client ID is' in data['Content']:
client_id = data['ReceiverId']
print(f"Assigned Client ID: {client_id}")
threading.Thread(target=receive_messages, args=(client_socket,client_id,), daemon=True).start()
threading.Thread(target=send_heartbeat, args=(client_socket, client_id,), daemon=True).start()
print("Enter command ('/list' to see clients, '/connect <client_id>' to start conversation, '/exit' to leave conversation, 'exit' to quit): ")
send_messages(client_socket, client_id)
client_socket.close()
if __name__ == "__main__":
main()