Simple Chat Room Application Using Python Socket

codepythonic
0

  Simple Chat Room Application Using  Python Socket



Server Code


import time
import socket
import sys

print("\nWelcome to the chat room")
print("\nInitializing....")

time.sleep(1)
s = socket.socket()
host = socket.gethostname()
ip = socket.gethostbyname(host)
port = 1234
s.bind((host, port))
print(host, "(", ip, ")\n")
name = input(str("Enter your name: "))

s.listen(3)
print("\nWaiting for incoming connections...")
conn, addr = s.accept()
print("\nReceived connection from", addr[0], "(", addr[1], ")")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has connected to the chat room")
conn.send(name.encode())

while True:
    message = input(str("Me: "))
    message_with_name = name + ": " + message
    conn.send(message_with_name.encode())
    received_message = conn.recv(1024)
    received_message = received_message.decode()
    print(s_name + ": " + received_message)



Client Code :



import socket
import time
import sys

print("\nWelcome to the chat room")
print("\nInitializing....")

time.sleep(1)
s = socket.socket()
shost = socket.gethostname()
ip = socket.gethostbyname(shost)
print(shost, "(", ip, ")\n")
host = input(str("Enter the server address to connect: "))
name = input(str("Enter your name: "))
port = 1234
print("\nTrying to connect to", host)
time.sleep(3)
s.connect((host, port))
print("Connected...\n")
s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")

while True:
    message = s.recv(1024)
    message = message.decode()
    print(message)
    message = input(str("Me: "))
    message_with_name = name + ": " + message
    s.send(message_with_name.encode())



Tags:

Post a Comment

0Comments

Post a Comment (0)