6
\$\begingroup\$

This is a Python chat room that I've been working on and it enables to you to chat to other people on the same network through Python.

Server.py:

import socket
import sys

s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")
conn.send(name.encode())

while 1:
    message = input(str("Please enter your message: "))
    conn.send(message.encode())
    print("Sent")
    print("")
    message = conn.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")

Client.py:

import socket
import sys

s = socket.socket()
host = input(str("Please enter the hostname of the server : "))
port = 8080
s.connect((host,port))
name = input(str("Please enter your username : "))
print(" Connected to chat server")

s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")

while 1:
    message = s.recv(1024)
    message = message.decode()
    print(s_name, ":" ,message)
    print("")
    message = input(str("Please enter your message: "))
    message = message.encode()
    s.send(message)
    print("Sent")
    print("")

I just wanted suggestions on how I can to improve this chatroom to make it better and faster. All suggestions will be greatly appreciated.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$
host = input(str("Please enter the hostname of the server : "))
...
message = input(str("Please enter your message: "))

can be changed to simply:

message = input("Please enter your message: ")
...
host = input("Please enter the hostname of the server : ")

since there is no need to cast a string to a string.

while 1:

is fine, but is more readable as:

while True:

Having print statements like the following:

print("")

is redundant. If you want an extra newline after a print statement; Add "\n" to the end of the preceding print statements to remove a function call, and reduce code clutter. E.G:

print("Sent\n")

This is more of a personal preference, but fstring formatting is more readable than the following:

print(s_name, ":" ,message)

should be:

print( f"{s_name}: {message}" )
\$\endgroup\$
0
-2
\$\begingroup\$

If we send two or more messages from any side at once, another side will receive only a single message at once rather than all.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.