我幾乎是Python Socket編程的初學者。我做了一個聊天服務器,但它不正確。聊天服務器引發TypeError:描述符'encode'需要'str'對象但收到'unicode'
它可以正常接收數據,但不適用於發送數據。當我使用'conn.send()'時,客戶端永遠不會收到消息。請幫幫我。
This is my code for the socket server:
'''
Simple socket server using threads
'''
import socket
import sys
from _thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created on Port: '+str(PORT))
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print ('Socket bind complete')
#Start listening on socket
s.listen(10)
print ('Socket now listening')
connectmsg = 'Welcome to OmniBean\'s Chat server!'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
print('Sending Welcome Message...')
#print(conn)
conn.send(str.encode(connectmsg)) #send only takes string ENCODED!
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = bytes.decode(conn.recv(1024))
print (data)
reply = 'OK...' + data
if not data:
break
conn.sendall(str.encode(reply))
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
conn.send(str.encode(connectmsg))
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close()
如果你能弄明白這是爲什麼,那麼你能告訴我嗎?我的客戶端代碼是在這裏: 我的客戶是使用SimpleNet Library從OmniBean
import os
from simplenet import *
myname = input ('Enter a login name: ')
host = input('Enter Host Name: ')
port = input('Enter Host Port: ')
connect(host,port)
welcome = receive()
input('Received Message: '+welcome)
while True:
os.system('cls')
#room = receive()
#print (room)
msg = input('Enter a message to send to server: ')
send(myname+': '+msg)
從理論上講,因爲我從服務器發送數據的兩倍,客戶端應該接收數據;然而,客戶端只是一直等待永遠不會來自服務器的消息。請幫助我解決這個問題。
'_thread'與'_thread import *'中的一樣? – Paul 2014-10-17 05:48:11
我用'thread'替換了'_thread',並用'telnet localhost 8888'作爲客戶端運行它。它給了我你好消息。在我輸入一個字符串後,python程序給出了一個錯誤:'File'chat.py',第42行,在clientthread中conn.sendall(str.encode(reply))TypeError:descriptor'encode'需要一個'str'對象,但收到'unicode' – Paul 2014-10-17 05:51:55
該問題目前不是客戶端/服務器問題。問題是'str.encode' – Paul 2014-10-17 05:55:46