Python Forum
Help! Chatting App - Changing the "IP & Port" into Username
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help! Chatting App - Changing the "IP & Port" into Username
#1
Hello guys, I need some help for my homework.
I'm a beginner in this programming.
In this case, I have to change a few things based on the code and requirements from my teacher.

Here's what it looks like :
   

what need to change :
  • Terminal 1 (Server) : How to change the "IP & Port" into username?
  • Terminal 2 & 3 (Client) : How to input username?
  • Changing the "IP & Port" showing in client side into username that user input?
  • And adding KeyboardInterrupt function in both server and client.

Here's the Server Code:
#!/usr/bin/env python2
# chat_server.py
 
import sys, socket, select

HOST = '' 
SOCKET_LIST = []
RECV_BUFFER = 4096 
PORT = 9001

def chat_server():

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((HOST, PORT))
    server_socket.listen(10)

    # add server socket object to the list of readable connections
    SOCKET_LIST.append(server_socket)

    print ("Chat server started on port " + str(PORT))

    while 1:

        # get the list sockets which are ready to be read through select
        # 4th arg, time_out  = 0 : poll and never block
        ready_to_read,ready_to_write,in_error = select.select(SOCKET_LIST,[],[],0)

        for sock in ready_to_read:
            # a new connection request recieved
            if sock == server_socket: 
                sockfd, addr = server_socket.accept()
                SOCKET_LIST.append(sockfd)
                print ("Client (%s, %s) connected" % addr)

                broadcast(server_socket, sockfd, ("[%s:%s] entered our chatting room\n" % addr))

            # a message from a client, not a new connection
            else:
                # process data recieved from client, 
                try:
                    # receiving data from the socket.
                    data = sock.recv(RECV_BUFFER)
                    if data:
                        # there is something in the socket
                        broadcast(server_socket, sock, ("\r" + '[' + str(sock.getpeername()) + '] ' + data.decode()))  
                    else:
                        # remove the socket that's broken    
                        if sock in SOCKET_LIST:
                            SOCKET_LIST.remove(sock)

                        # at this stage, no data means probably the connection has been broken
                        broadcast(server_socket, sock, ("Client (%s, %s) is offline\n" % addr)) 

                # exception 
                except:
                    broadcast(server_socket, sock, "Client (%s, %s) is offline\n" % addr)
                    continue

    server_socket.close()

# broadcast chat messages to all connected clients
def broadcast (server_socket, sock, message):
    for socket in SOCKET_LIST:
        # send the message only to peer
        if socket != server_socket and socket != sock :
            try :
                socket.send(message.encode())
            except :
                # broken socket connection
                socket.close()
                # broken socket, remove it
                if socket in SOCKET_LIST:
                    SOCKET_LIST.remove(socket)

if __name__ == "__main__":
    sys.exit(chat_server())
Here's the Client Code :
#!/usr/bin/env python2
# chat_client.py

import sys, socket, select
from threading import *

def send_msg(s):
    while True:
        msg = sys.stdin.readline()
        s.send(msg.encode())
        sys.stdout.write('[Me] '); sys.stdout.flush()

def recv_msg(sock):
    while True:
        data = sock.recv(4096)
        if not data :
            print ('\nDisconnected from chat server')
            sys.exit()
        else :
            #print data
            sys.stdout.write(data.decode())
            sys.stdout.write('[Me] '); sys.stdout.flush()


def chat_client():
    if(len(sys.argv) < 3) :
        print ('Usage : python3 chat_client_v1.py hostname port')
        sys.exit()

    host = sys.argv[1]
    port = int(sys.argv[2])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print ('Unable to connect')
        sys.exit()

    print ('Connected to remote host. You can start sending messages')
    sys.stdout.write('[Me] '); sys.stdout.flush()

    Thread(target=send_msg, args=(s,)).start()
    Thread(target=recv_msg, args=(s,)).start()

if __name__ == "__main__":
    sys.exit(chat_client())
Please help!
I'm totally clueless.
And thank you in advance.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  function-decorator , which is checking an access according to USERNAME Liki 6 593 Feb-17-2024, 03:36 AM
Last Post: deanhystad
  python code tp determin a userName and print message jackAmin 4 1,859 Nov-20-2022, 12:03 AM
Last Post: rob101
  Password and Username Verification AlwaysNew 4 17,209 Nov-12-2017, 11:51 AM
Last Post: wavic
  Username and password Steve2017 13 9,822 Sep-03-2017, 09:17 PM
Last Post: Steve2017

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020