TypeError:尽管将.encode()添加到字符串

时间:2017-07-17 13:24:03

标签: python string python-3.x sockets

我正在尝试编写一些连接到IRC频道的代码,并允许用户通过频道进行聊天。我的脚本连接到服务器时出现错误:

TypeError: Can't convert 'bytes' object to str implicitly

错误显然在第18行,即将昵称发送到服务器的代码:

irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")

源代码:

import sys
import socket

server = "chat.freenode.net"
channel = "#randomchannel123456789"
port = 7070

print("IRC Connecter")
print("-----------------------------")
nick = input("Input Nickname: ")

irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("connecting to " + server)

irc.connect((server, port))
print("connected")

irc.send("USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n")
print("sent user")

irc.send ("NICK " + nick + "\n")
print("sent nick")

while 1:
   text = irc.recv(2040)
   print(text)

   if text.find("PING") != -1:
      irc.send("PONG " + text.split() [1] + "\r\n")

我对套接字编程很新,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

问题在于:

"USER " + nick.encode() + " " + nick.encode() + " " + nick.encode() + " : Test\n"

"USER "" "" : Test\n"str,但nick.encodebytes个对象。例外情况告诉您,您无法添加bytesstr s:

>>> b'a' + 'a'
TypeError: can't concat bytes to str

>>> 'a' + b'a'
TypeError: Can't convert 'bytes' object to str implicitly

您可以将字符串文字转换为字节,例如使用字节文字(b""):

b"USER " + nick.encode() + b" " + nick.encode() + b" " + nick.encode() + b" : Test\n"