我一直在嘗試一切,我可以運行此代碼,但我無法弄清楚是什麼問題。這是一個服務器/客戶端聊天程序在python 3中。我得到的錯誤是:NameError:名稱'記錄'未定義。 Python 3
Traceback (most recent call last):
File "/home/nate/Desktop/soc_chat/server_soc.py", line 48,<module>
handler = ClientHandler(client, record)
NameError: name 'record' is not defined
我不知道如何解決此問題。任何幫助都會很棒。我在Ubuntu上,安裝了python 3。我已經嘗試在終端中運行代碼爲'python3 myFile.py',而不是'python myFile.py',以確保它不會像python 2那樣運行它。正如我所說的,任何幫助都將不勝感激。
下面的代碼(服務器端):
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(bytes('Welcome', CODE))
self._name = decode(self._client.recv(BUFSIZE), CODE)
self._client.send(bytes(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(bytes(str(self._record), CODE))
HOST = 'localhost'
PORT = 5000
BUFSIZE = 1024
ADDRESS = (HOST, PORT)
CODE = 'ascii'
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 = input('Enter your name: ')
server.send(bytes(name, CODE))
while True:
record = decode(server.recv(BUFSIZE), CODE)
if not record:
print('server disconnected')
break
print(record)
message = input('> ')
if not message:
print('Server disconnected')
break
server.send(bytes(message, CODE))
server.close()
代碼(chatrecord.py)
class ChatRecord(object):
def __init__(self):
self.data = []
def add(self, s):
self.data.appent(s)
def __str__(self):
if len(self.data) == 0:
return 'No messages yet!'
else:
return '\n'.join(self.data)
所以,你能指望什麼'record'是?您在調用'ClientHandler'時沒有定義它.. .. – 2015-03-02 19:27:48