Skip to content

Commit

Permalink
Merge pull request #68 from AvishkaWeebadde/avishka
Browse files Browse the repository at this point in the history
A simple TCP chatting client with python
  • Loading branch information
AyanSaha25 authored Oct 26, 2020
2 parents 4e65a21 + b610ddc commit 3ac482d
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
39 changes: 39 additions & 0 deletions TCP_chatroom/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import socket
import threading

alias = input("choose a alias/nickanme: ")

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('127.0.0.1', 55556))

# sending alias to the server
def receive():
while True:
try:
message = client.recv(1024).decode('ascii')
if message == 'NICK':
client.send(alias.encode('ascii'))
else:
print(message)

except:
print("An error occured!")
client.close()
break

# sending messages
def write():
while True:
message ='{}: {}'.format(alias, input(''))
client.send(message.encode('ascii'))


receive_thread = threading.Thread(target=receive)
receive_thread.start()

write_thread = threading.Thread(target=write)
write_thread.start()




58 changes: 58 additions & 0 deletions TCP_chatroom/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import threading
import socket


host = '127.0.0.1'
port = 55556

# Starting Server
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen()

clients = []
aliases = []

def broadcast(message): # send the message to whole network
for client in clients:
client.send(message)


def handle(client):
while True:
try:
message = client.recv(1024)
broadcast(message)
except:
index = clients.index(client)
clients.remove(client)
client.close()
alias = aliases[index]
broadcast(f'{alias} left the chat'.encode('ascii'))
aliases.remove(alias)
break

def receive():
while True:
client, address = server.accept() # confirm connection
print(f'connected with {str(address)}')

client.send('NICK'.encode('ascii')) # nickname storage
alias = client.recv(1024).decode('ascii')
aliases.append(alias)
clients.append(client)

print(f'Nickname of the client is {alias}')
broadcast(f'{alias} joined the chat!'.encode('ascii'))
client.send('Connected to the server!'.encode('ascii'))


thread = threading.Thread(target=handle, args=(client,))
thread.start()



print("server is listening")
receive()


0 comments on commit 3ac482d

Please sign in to comment.