Search code examples
pythonpython-3.xnetwork-programmingtcpclientp2p

How to fix "IndexError: list index out of range" error of p2p chat application on Python?


I am doing p2p chat application by Python. There is a error at "message = inputt[1]" on client side. Because of this error when i want to send message the program prints "You must write your name "

I dont know how to solve because i didnt understand the logic of the mistake. It will be great if i can get the explanation of why i am getting this error and the solution.

import socket
import json
import time
import threading
import datetime

onlineUsers = dict()

while True:

    message = input()

    if(message=='list'):
        print('ONLINE USERS...')
        for key in onlineUsers:
            print(key)

    else:

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


        try:
            inputArray = message.split(':',1)
            # 0=username  1=message
            username=inputArray[0]
            message=inputArray[1]
            ip=onlineUsers[username]
            s.connect((ip, port))
            s.sendall(message)

        except:
            print("You must write your name <name: message >")

        s.close()

Solution

  • I think the clue to what went wrong is in the question itself. The print statement says "You must write your name <name: message >", so your message will be john : this is a test, but instead you are sending this is a test, which when you split on : will give you a single element list ['this is a test'] and when you try to get the second index of this list, you get the IndexError: list index out of range

    So if you fix your message to match the format expected, the code should work as follows

    message = 'john : this is a test'
    inputArray = message.split(':')
    # 0=username  1=message
    username = inputArray[0].strip()
    message = inputArray[1].strip()
    print(username)
    print(message)
    

    The output will be

    john
    this is a test