聊天服务器引发TypeError:描述符'encode'需要'str'对象,但接收到'unicode

2 投票
2 回答
15312 浏览
提问于 2025-04-28 01:21

我对Python的Socket编程还是个初学者。我做了一个聊天服务器,但它运行得不太对。

接收数据的部分没问题,但发送数据时就出问题了。当我使用'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库,这个库来自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)

理论上来说,因为我从服务器发送了两次数据,客户端应该能收到这些数据;然而,客户端却一直在等待服务器的消息,但消息就是不来。请帮我解决这个问题。

暂无标签

2 个回答

0

我在使用pyarrow里的pybytes时遇到了这个问题,后来通过使用 str(bybytes) 解决了这个问题。

5

这不是一个客户端/服务器的问题。

我在测试你的脚本时遇到的实际错误是:

文件 "chat.py",第42行,在 clientthread 中 conn.sendall(str.encode(reply)) 类型错误: 描述符 'encode' 需要一个 'str' 对象,但收到了 'unicode'

通常,当出现问题时,提供完整的错误信息会很有帮助……

我在谷歌上搜索了一下这个错误,并查看了这个讨论:Python - 描述符 'split' 需要一个 'str' 对象,但收到了 'unicode'

我把

conn.sendall(str.encode(reply))

改成了

conn.sendall(reply.encode('ascii'))

现在用 telnet localhost 8888 作为客户端时,它运行得很好。

撰写回答