Question

I have made a chat program (in this moment only host can send messages):

server:

# server
import socket

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

host = 'localhost'
port = 150

server.bind((host, port))

print 'Server is open\nWaiting connections...'

server.listen(1)

while True:
    client, addr = server.accept()
    print 'Connected by', addr
    while True:

HERE IS THE PROBLEM:when i type messages and i send they , the client see only messages with a even number. why this happen?

        msg = raw_input('>>>')
        if msg == 'exit':
            client.send(msg)
            break
        else:
            client.send('<Host>' + msg)
client.close()

client:

# client
import socket
import time

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

host = 'localhost'
port = 150

client.connect((host,port))

while True:
    if client.recv(1024) == 'exit':
        print '<System>Host disconnected the Server...'
        print '<System>Program will shoot down in 5 seconds'
        time.sleep(5)
        break
    else:
        print client.recv(1024)
client.close()
Was it helpful?

Solution

Note that you receive the message twice in the client: First, you receive a message and check whether it's the "exit" message, then a second message is received and printed. Thus, only the even messages are printed, while the odd ones are used up in the if condition.

Try changing the client code to this:

while True:
    msg = client.recv(1024)
    if msg == 'exit':
        print '<System>Host disconnected the Server...'
        print '<System>Program will shut down in 5 seconds'
        time.sleep(5)
        break
    else:
        print msg
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top