-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
110 lines (91 loc) · 2.89 KB
/
client.py
File metadata and controls
110 lines (91 loc) · 2.89 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
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
import socket
import struct
from threading import Thread
import time
import getch
Bold = "\033[1m"
Red = "\033[31;1m"
Green = "\033[32;1m"
Yellow = "\033[33;1m"
Blue = "\033[34;1m"
end = "\033[0;1m"
def startingThread(sock):
try:
endtime = time.time()+10
while time.time() < endtime:
try:
sock.settimeout(max(0, endtime - time.time()))
intosend = getch.getch()
sock.sendall(intosend.encode())
except:
pass
except:
pass
# print('\nfineshed this round')
def ScoreOutput(sock):
try:
endtime = time.time()+10
while time.time() < endtime:
output = sock.recv(1024)
if output:
print(output.decode('utf-8'))
except Exception as e : print(e)
def Main():
TEAM_NAME = f"{Yellow}Bugs Bunny\n{end}"
print(f"{Green}Client started,listening for offer requests...\n{end}")
client = UDPConn()
try:
client.bind(("", 13117))
except:
print(f"{Red}error binding{end}")
while True:
data1, addr = client.recvfrom(1024)
host, UDP_Port = addr
try:
data1, data2 , TCP_Port = struct.unpack('!IBH', data1)
if data1 == 0xfeedbeef and data2 == 0x2: # checking recieved message from broadcast
print(f"{Green}received offer from{end}", host, f"{Green},attempting to connect...\n{end}")
sock = TCPConn(TCP_Port, host)
try:
sock.sendall(TEAM_NAME.encode('utf-8'))
SendDataByThread(sock)
# ScoreOutput(sock)
except:
print(f"{Red}server closed{end}")
finally:
sock.close()
except:
pass
def TCPConn(TCP_Port, host):
# TCP
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (host, TCP_Port)
try:
sock.connect(server_address)
except:
print(f"{Red}connection failed{end}")
return sock
def SendDataByThread(sock):
DataIsFound = False
endtime = time.time()+10
while time.time() < endtime and not DataIsFound:
data = sock.recv(1024)
if data is not None:
print(data.decode('utf-8'))
# create the thread of sending
thread = Thread(target=startingThread, args=(sock,))
thread.start()
thread.join()
thread2 = Thread(target=ScoreOutput, args=(sock,))
thread2.start()
thread2.join()
DataIsFound = True
# else:
# DataIsFound = False
def UDPConn():
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
return client
if __name__ == '__main__':
Main()