-3

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

客户端.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()

服务器.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()
4

1 回答 1

2

您已经切换了accept的结果元组:

addr,obj = s.accept()

应该

obj,addr = s.accept()

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

在不相关的注释中,您可能希望有一个比obj. 怎么client_socksock

还,

msg = addr + msg

将失败,因为 addr 是一个元组,而 msg 是一个字节串。你要

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

此外,

del message

只是删除 name message,并且在您的情况下是无操作的。您可能想Queue.get改用。

于 2012-11-12T18:29:47.973 回答