我几乎是 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 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)
理论上,由于我从服务器发送了两次数据,所以客户端应该收到数据;然而,客户端只是永远等待来自服务器的消息,但永远不会到来。请帮我解决这个问题。
最佳答案
这不是客户端/服务器问题。
我在测试您的脚本时收到的实际错误是:
File "chat.py", line 42, in clientthread conn.sendall(str.encode(reply)) TypeError: descriptor 'encode' requires a 'str' object but received a 'unicode'
通常,出现问题时发布完整的错误消息会很有用......
对错误进行一些谷歌搜索并关注 Python - Descriptor 'split' requires a 'str' object but received a 'unicode' 上的讨论
我变了
conn.sendall(str.encode(reply))
到
conn.sendall(reply.encode('ascii'))
现在,我使用 telnet localhost 8888
作为客户端,效果很好。
关于python - 聊天服务器引发 TypeError : descriptor 'encode' requires a 'str' object but received a 'unicode' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26416445/