■ ■ ■ ■ ■ ■
Projects/1_TCP_chat_server/TCPserver.py
| 1 | + | import socket |
| 2 | + | import threading |
| 3 | + | import sys |
| 4 | + | |
| 5 | + | # checks whether sufficient arguments have been provided |
| 6 | + | if len(sys.argv) != 3: |
| 7 | + | print ("Correct usage: script, IP address, port number") |
| 8 | + | exit() |
| 9 | + | |
| 10 | + | # takes the first argument from command prompt as IP address |
| 11 | + | host = str(sys.argv[1]) |
| 12 | + | |
| 13 | + | # takes second argument from command prompt as port number |
| 14 | + | port = int(sys.argv[2]) |
| 15 | + | |
| 16 | + | # Starting Server |
| 17 | + | server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 18 | + | server.bind((host, port)) |
| 19 | + | server.listen() |
| 20 | + | |
| 21 | + | # Lists For Clients and Their Nicknames |
| 22 | + | clients = [] |
| 23 | + | nicknames = [] |
| 24 | + | |
| 25 | + | # Sending Messages To All Connected Clients |
| 26 | + | def broadcast(message): |
| 27 | + | for client in clients: |
| 28 | + | client.send(message) |
| 29 | + | |
| 30 | + | # Handling Messages From Clients |
| 31 | + | def handle(client): |
| 32 | + | while True: |
| 33 | + | try: |
| 34 | + | # Broadcasting Messages |
| 35 | + | message = client.recv(1024) |
| 36 | + | broadcast(message) |
| 37 | + | except: |
| 38 | + | # Removing And Closing Clients |
| 39 | + | index = clients.index(client) |
| 40 | + | clients.remove(client) |
| 41 | + | client.close() |
| 42 | + | nickname = nicknames[index] |
| 43 | + | broadcast('{} left!'.format(nickname).encode('utf-8')) |
| 44 | + | nicknames.remove(nickname) |
| 45 | + | break |
| 46 | + | |
| 47 | + | # Receiving / Listening Function |
| 48 | + | def receive(): |
| 49 | + | while True: |
| 50 | + | # Accept Connection |
| 51 | + | client, address = server.accept() |
| 52 | + | print("Connected with {}".format(str(address))) |
| 53 | + | |
| 54 | + | # Request And Store Nickname |
| 55 | + | client.send('NICK'.encode('utf-8')) |
| 56 | + | nickname = client.recv(1024).decode('utf-8') |
| 57 | + | nicknames.append(nickname) |
| 58 | + | clients.append(client) |
| 59 | + | |
| 60 | + | # Print And Broadcast Nickname |
| 61 | + | print("Nickname is {}".format(nickname)) |
| 62 | + | broadcast("{} joined!".format(nickname).encode('utf-8')) |
| 63 | + | client.send('Connected to server!'.encode('utf-8')) |
| 64 | + | |
| 65 | + | # Start Handling Thread For Client |
| 66 | + | thread = threading.Thread(target=handle, args=(client,)) |
| 67 | + | thread.start() |
| 68 | + | |
| 69 | + | print('-----Server UP-----') |
| 70 | + | receive() |