-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchatClient.py
More file actions
47 lines (36 loc) · 1.35 KB
/
chatClient.py
File metadata and controls
47 lines (36 loc) · 1.35 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
from socket import *
import sys
# function for receiving message from client
def send_to_server(clsock):
send_msg = input('Type Message: ')
clsock.sendall(send_msg.encode())
# function for receiving message from server
def recv_from_server(clsock):
data = clsock.recv(1024).decode()
if data == 'q':
print('Closing connection')
sys.exit()
print('Message Received: ', data)
# this is main function
def main():
# TODO (1) - define HOST name, this would be an IP address or 'localhost' (1 line)
HOST = 'localhost'
# TODO (2) - define PORT number (1 line) (Google, what should be a valid port number)
PORT = 12345
# Create a TCP client socket
#(AF_INET is used for IPv4 protocols)
#(SOCK_STREAM is used for TCP)
# TODO (3) - CREATE a socket for IPv4 TCP connection (1 line)
clientSocket = socket(AF_INET, SOCK_STREAM)
# request to connect sent to server defined by HOST and PORT
# TODO (4) - request a connection to the server (1 line)
clientSocket.connect((HOST, PORT))
print('Client is connected to a chat server!\n')
while True:
# call the function to send message to server
send_to_server(clientSocket)
# call the function to receive message server
recv_from_server(clientSocket)
# This is where the program starts
if __name__ == '__main__':
main()