-
Notifications
You must be signed in to change notification settings - Fork 0
/
clients.py
45 lines (34 loc) · 1.27 KB
/
clients.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
import socket
import sys
import threading
# function send_message() to send message to the server
def send_message(clientSock):
# input client's username as identity
username = input("Input username: ")
# input message and send it to the server
while True:
message = input()
message_send = username + ': ' + message
clientSock.sendto(message_send.encode("utf-8"), (UDP_IP_ADDRESS, UDP_PORT_NO))
# to delete message input
sys.stdout.write("\033[F")
# declare ip address and port
UDP_IP_ADDRESS = '0.0.0.0'
UDP_PORT_NO = 2410
# create socket
clientSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# allows sockets to bind() to the same IP:port
clientSock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
# allows broadcast UDP packets to be sent and received
clientSock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
# bind the socket to address
clientSock.bind((UDP_IP_ADDRESS, UDP_PORT_NO))
# print additional message
print("\nWelcome to WhatsUDP Messenger!")
# create object Thread
clientThread = threading.Thread(target=send_message, args=(clientSock,))
clientThread.start()
# receive broadcast message from server and print it
while True:
data, addr = clientSock.recvfrom(1024)
print(data.decode("utf-8"))