Python Mutli-chat套接字错误

时间:2016-08-16 19:14:49

标签: python multithreading python-3.x

我正在编写一个多聊天,其中包括客户端处理程序,服务器和聊天记录。客户应该允许多个聊天。目前它甚至不允许进行一次聊天,我在输入名称后收到错误消息。

这是客户端处理程序文件

from socket import*
from codecs import decode
from chatrecord import ChatRecord
from threading import Thread
from time import ctime

class ClientHandler (Thread):

def __init__(self, client, record):
     Thread.__init__(self)
     self._client = client
     self._record = record

def run(self):
    self._client.send(str('Welcome to the chatroom!'))
    self._name = decode(self._client.recv(BUFSIZE),CODE)
    self._client.send(str(self._record),CODE)
    while True:
        message = decode(self._client.recv(BUFSIZE),CODE)
        if not message:
            print('Client disconnected')
            self._client.close()
            break
        else:
            message=self._name +'' + \
                    ctime()+'\n'+message
            self._record.add(message)
            self._client.send(str(self._record),CODE)

HOST ='localhost'
PORT = 5000
ADDRESS = (HOST,PORT)
BUFSIZE = 1024
CODE = 'ascii'
record = ChatRecord()
server = socket(AF_INET,SOCK_STREAM)
server.bind(ADDRESS)
server.listen(5)

while True:
    print ('Waiting for connection...')
    client,address = server.accept()
    print ('...connected from:',address)
    handler = ClientHandler(client,record)
    handler.start() 

这是服务器文件

from socket import *
from codecs import decode

HOST ='localhost'
PORT = 5000
BUFSIZE = 1024
ADDRESS = (HOST,PORT)
CODE = 'ascii'

server = socket(AF_INET,SOCK_STREAM)
server.connect(ADDRESS)
print (decode(server.recv(BUFSIZE), CODE))
name = raw_input('Enter your name:')
server.send(name)

while True:
    record = server.recv(BUFSIZE)
    if not record:
        print ('Server disconnected')
        break
    print (record)
    message = raw_input('>')
    if not message:
        print ('Server disconnected')
        break
    server.send(message, CODE)
server.close()

这是Chartrecord

class ChatRecord(object):
def __init__(self):
    self.data=[]
def add(self,s):
    self.data.append(s)
def __str__(self):
    if len(self.data)==0:
        return 'No messages yet!'
    else:
        return'\n'.join(self.data)

这是我在运行聊天记录时收到的错误消息。我可以输入一个名称然后我得到下面的错误信息

Waiting for connection...
('...connected from:', ('127.0.0.1', 51774))
Waiting for connection...
Exception in thread Thread-1:
Traceback (most recent call last):
  File     "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/threadin g.py", line 532, in __bootstrap_inner
self.run()
  File "/Users/basetsanamanele/Documents/workspace/HAAAAAAAFF/ClientHandler", line 17, in run
self._client.send(str(self._record),CODE)
TypeError: an integer is required

请协助

1 个答案:

答案 0 :(得分:0)

修改:此外,您的服务器不接受/列出连接

您应该使服务器成为多线程,以便它可以同时发送和接收。以下是它的外观:

import socket
import os
from threading import Thread
import thread

def main():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((host,port))
    s.listen(10)
    serverThreads = []

    while True:
        print "Server is listening for connections..."
        client, address = s.accept()
        serverThreads.append(Thread(target=runserver, args=(client,address)).start())
    s.close()

def runserver(client, address):
    clients = set()
    lockClients = threading.Lock()
    print ("Connection from: " + address)
    with lockClients:
        clients.add(client)
    try:    
        while True:
            data = client.recv(1024)
            if data:
                print data.decode()
                with lockClients:
                    for c in clients:
                        c.sendall(data)
            else:
                break
    finally:
        with lockClients:
            clients.remove(client)
            client.close()

通过TCP发送字符串时,需要将其编码为字节。所以你的客户端文件应该是这样的:

def run(self):
    self._client.send(('Welcome to the chatroom!').encode())
    self._name = self._client.recv(BUFSIZE).decode()
    self._client.send(str(self._record),CODE)
    while True:
        message = self._client.recv(BUFSIZE).decode()
        if not message:
            print('Client disconnected')
            self._client.close()
            break
        else:
            message=self._name +'' + \
                    ctime()+'\n'+message
            self._record.add(message)
            self._client.send(self._record.encode())

我更喜欢.encode().decode()语法,因为它使代码更具可读性。