为什么我的客户端/服务器不工作?

时间:2012-11-12 18:23:16

标签: python sockets

当我一起运行客户端/服务器并尝试发送消息时,似乎他们中的任何一个都没有收到任何信息。为什么呢?

client.py:

import socket, sys
import threading

# Client for WutChat #

PORT = 5000

queue = []

def exitClient(s):
    s.close()
    print "Exiting..."
    sys.exit()

def connect(host, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try: s.connect((host, port))
    except: return "error"
    return s

def recieveData(s):
    while True:
        data = s.recv(512)
        if not data: continue
        if data in queue:
            continue
        queue.append(data)
        print data

def sendData(s):
    while True:
        try: data = raw_input(">")
        except EOFError: exitClient(s)
        if data == "": print "no msg"; continue;
        if data.startswith("/"):
            print "Command detected"
            continue
        s.send(data)

if __name__ == "__main__":
    s = connect(sys.argv[1], int(sys.argv[2]))
    threading.Thread(target=recieveData, args=(s,)).start()
    threading.Thread(target=sendData, args=(s,)).start()

server.py:

import socket, sys
import threading

# Server for WutChat #

PORT = 5000
DEBUG = True

conns = {}
msgqueue = []

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try: s.bind(("", int(sys.argv[1])))
    except IndexError: s.bind(("", PORT))
    s.listen(1)

    while True:
        addr, obj = s.accept()
        conns[addr] = obj

        print str(addr)+" connected!"

        threading.Thread(target=handle, args=(addr, obj, s,)).start()


def handle(addr, obj, s):
    while True:
        try: msg = obj.recv(512)
        except:
            continue

        print msg
        msg = addr + msg

        msgqueue.append(msg)
        if DEBUG: print msgqueue

        for conn in conns:
            for message in msgqueue:
                conns[conn].send(message)
                del message

if __name__ == "__main__":
    connect()

1 个答案:

答案 0 :(得分:2)

您已切换accept生成的元组:

addr,obj = s.accept()

应该是

obj,addr = s.accept()

要查找这些错误,请删除handle中的通用try..except块,并仅捕获您想要的特定错误。在您的特定情况下(如果obj.recv失败),您可以捕获 socket.error,但发生这种情况时唯一明智的做法是关闭套接字并终止线程。

在不相关的说明中,您可能希望使用比obj更具描述性的名称。 client_sock或仅sock怎么样?

此外,

msg = addr + msg

将失败,因为addr是一个元组,而msg是一个bytestring。你想要

msg = repr(addr).encode('utf-8') + msg

此外,

del message

只删除名称message,在您的情况下为no-op。您可能希望改为使用Queue.get