“must be str, not bytes”

后端 未结 2 1756
清歌不尽
清歌不尽 2021-01-29 09:06

I wrote a server on python:

import  socket
server_socket = socket.socket()
server_socket.bind((\'0.0.0.0\', 8820))

server_socket.listen(1)

(client_socket, clie         


        
相关标签:
2条回答
  • 2021-01-29 09:24

    You need to encode before sending a string. Example:

    mySocket.send("Hello".encode() + Client_name.encode())
    

    Or:

    mySocket.send(b"Hello" + Client_name.encode())
    
    0 讨论(0)
  • 2021-01-29 09:36

    Use encode/decode to convert between str and bytes before sending and after receiving:

    my_socket.send('Sami'.encode('utf-8'))  # encode string before sending
    data = my_socket.recv(1024).decode('utf-8')  # decode string after receiving
    

    You can replace 'utf-8' with other character encodings depending on your use case (you might see 'cp1252' used in Windows applications, for instance).

    For the server, rather than decoding the string and encoding it again after putting 'Hello ' on the front, you can skip a step and do this:

    client_name = client_socket.recv(1024)
    client_socket.send(b'Hello ' + client_name)
    

    b'Hello' is a literal bytes object, rather than a str object like 'Hello'. So b'Hello' + client_name will do bytes + bytes = bytes directly, rather than converting client_name to str with .decode, adding 'Hello' to get another str and then converting back to bytes with .encode.

    0 讨论(0)
提交回复
热议问题