I am working on making my own chat server and client, but have reached a little hiccup. The first line of text that the client send is not displayed by the server. Everything else is, just not the first line.
Client

import socket
uname = raw_input('username:> ')
uname = uname + ': '
host = raw_input('host name:> ')
port = 51423

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
data = raw_input(':> ')
s.send('\r\n')
while data != '/exit':
    data = raw_input(':> ')

    s.send(uname + data + "\r\n")

s.shutdown(1)

Server

import socket, traceback, sys

host = ''
port = 51423

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)

while 1:
    try:
        clientsock, clientaddr = s.accept()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
        continue

    #clientsock.settimeout(60)

    # Process the connection
    try:
        print "Connection received from", clientsock.getpeername()
        while 1:
            data = clientsock.recv(1024)
            if not len(data):
                break
            sys.stdout.write(data)
    except (KeyboardInterrupt, SystemExit):
        raise
    #except socket.timeout():
        print 'connection timed out'
    except:
        traceback.print_exc()

    # Close the connection
    try:
        clientsock.close()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()

The problem was that the first data = raw_input(':> ') is never sent

only the one that appears inside the while data !="/exit" loop is sent.
So obviously that first data is never displayed on the server side :-)

Solution 1: to set the first data assignment an empty string "" ex:
data =""

Solution 2 (breaks the DRY principle):
replace s.send('\r\n')
with
s.send(uname + data + "\r\n")

import socket
uname = raw_input('username:> ')
uname = uname + ': '
host = raw_input('host name:> ')
port = 51423

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

##### You don't want this here it never gets sent it just eats your first data
#data = raw_input(':> ')
#####
data=""
s.send('\r\n')
while data != '/exit':
data = raw_input(':> ')

s.send(uname + data + "\r\n")

s.shutdown(1)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.