聊天程序 - 发送不起作用

时间:2014-01-12 14:42:13

标签: python send

我做了一个聊天程序(此时只有主持人可以发送消息):

服务器:

# 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:

这就是问题:当我输入消息并发送消息时,客户端只会看到带有偶数的消息。为什么会这样?

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

客户端:

# 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()

1 个答案:

答案 0 :(得分:4)

请注意,您在客户端收到消息两次:首先,您收到一条消息并检查它是否是“退出”消息,然后收到第二个消息并打印。因此,只打印偶数消息,而奇数消息在if条件下用完。

尝试将客户端代码更改为:

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