我遇到了让游戏正常运行并一次接受多个连接的问题。在我的server.py
中,while word:
循环中有一个print语句,我无法将其作为消息发送给客户端。我一直在尝试不同的事情,但继续'AttributeError: NoneType object has no attribute encode'
。
print语句扰乱了这个词。从那里,你可以猜测看看这个未被解读的单词是什么。
client.py
import sys
from socket import * # portable socket interface plus
constants
serverHost = 'localhost'
serverPort = 50007
message = [b'Hello network world'] # default text to send to server
# requires bytes: b'' or str,encode()
if len(sys.argv) > 1:
serverHost = sys.argv[1] # server from cmd line arg 1
sockobj = socket(AF_INET, SOCK_STREAM) # make a TCP/IP socket object
sockobj.connect((serverHost, serverPort)) # connect to server machine + port
while True:
# receive line from server: up to 1k
servResponse = sockobj.recv(1024).decode()
if not servResponse:
break
print(servResponse)
if(servResponse == '\nType your answer: '):
nextWord = raw_input('')
sockobj.send(nextWord.encode())
sockobj.close()
server.py
import time, _thread as thread, random
from socket import *
file = open("wordlist.txt", "r")
wordlist = file.readlines()
file.close()
myHost = ''
myPort = 50007
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(5)
def handleClient(connection):
word = wordlist[random.randrange(len(wordlist))]
while len(word) > 5 or len(word) == 0:
word = wordlist[random.randrange(0, len(wordlist))]
word = word.rstrip()
old_word = word
word = list(word)
connection.send(("Jumble game starting...").encode())
while word:
print(word.pop(random.randrange(len(word))), end=' ')
connection.send(('\nType your answer: ').encode())
#connection.send(('Testing: ').encode())
userAnswer = (connection.recv(1024).decode())
print('testing')
new_word = userAnswer + '\n'
if new_word in wordlist and set(userAnswer) == set(old_word):
connection.send(("\nYou win.").encode())
else:
connection.send(("\nThe word is " + old_word).encode())
connection.close()
def dispatcher(): # listen until process killed
while True: # wait for next connection,
connection, address = sockobj.accept()
thread.start_new_thread(handleClient, (connection,))
dispatcher()
非常感谢任何帮助。