-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path76. Simple Chat Application (Using Socket Programming).py
More file actions
54 lines (42 loc) · 1.22 KB
/
76. Simple Chat Application (Using Socket Programming).py
File metadata and controls
54 lines (42 loc) · 1.22 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
48
49
50
51
52
53
54
import socket
def server():
host = '127.0.0.1'
port = 12345
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)
print("Server listening on port:", port)
conn, addr = server_socket.accept()
print("Connected to:", addr)
while True:
message = conn.recv(1024).decode()
if not message:
break
print("Client:", message)
reply = input("Server: ")
conn.send(reply.encode())
conn.close()
server_socket.close()
def client():
host = '127.0.0.1'
port = 12345
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((host, port))
while True:
message = input("Client: ")
client_socket.send(message.encode())
if message.lower() == 'bye':
break
reply = client_socket.recv(1024).decode()
print("Server:", reply)
client_socket.close()
def main():
role = input("Enter your role (server/client): ")
if role.lower() == 'server':
server()
elif role.lower() == 'client':
client()
else:
print("Invalid role")
if __name__ == "__main__":
main()