套接字模块发送和接收类型错误

时间:2018-12-07 23:00:17

标签: python python-3.x sockets

>>> client.send('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> client.send('hello').encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> client.send('hello').encode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'

客户端已连接,并且处于接收模式data=mysocket.recv(2048)中,我尝试对字符串进行编码,但似乎不起作用,我还尝试发送整数值,但遇到相同的错误。 这是收件人

import socket
mysocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
mysocket.connect(('192.168.*.**',4444))
data=mysocket.recv(2048)

我必须** IP地址

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('192.168.*.**',4444))
s.listen(5)
(client,(ip,port))=s.accept()
client.send('hello world')

我该如何解决?

1 个答案:

答案 0 :(得分:2)

我建议的代码(未经完全测试):

#SERVER
import socket

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as s:
    s.bind(('192.168.*.**',4444))
    s.listen(0)
    conn, client_addr= s.accept()
    print('The client:', client_addr, s.gethostbyaddr(client_addr[0]),'\n')

    with conn:
        while True:
            data = conn.recv(1024)  
            print('received:',data)
            if not data: # 'data' will be empty '' if the client closed the connection.
                print("exit")
                break

            conn.sendall(b'Hello World!') 

#CLIENT
import socket

with socket.socket(SockParam.FAMILY, SockParam.TYPE) as mysocket:

    mysocket.connect(('192.168.*.**',4444))
    print("The connection is established.")    
    data=mysocket.recv(2048)

    for msg in ["python","stackoverflow"]:

        sock.sendall( bytes(msg,encoding="utf8") )
        ackn = sock.recv(1024)          # waiting for the server
        print("echoed:",ackn )

例如,您可以使用big endian发送4字节整数:

sock.sendall( int.to_bytes(42,4,'big') )