-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.py
44 lines (39 loc) · 1.19 KB
/
client.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
import socket
import threading
import sys
#Wait for incoming data from server
#.decode is used to turn the message in bytes to a string
def receive(socket, connected = True):
while connected:
try:
data = b''
while True:
chunk = socket.recv(4096)
data += chunk
if len(chunk) < 4096:
break
if data:
print(str(data.decode('utf-8')))
except:
print("You have been disconnected from the server")
connected = False
break
#Get host and port
host = input("Host: ")
port = int(input("Port: "))
#Attempt connection to server
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
except:
print("Could not make a connection to the server")
input("Press enter to quit")
sys.exit(0)
#Create new thread to wait for data
receiveThread = threading.Thread(target = receive, args = (sock, True))
receiveThread.start()
#Send data to server
#str.encode is used to turn the string message into bytes so it can be sent across the network
while True:
message = input()
sock.sendall(str.encode(message))