Exception in thread Thread-10 error in write function, TypeError: write() argument must be str, not bytes

Exception in thread Thread-10 error in write function, TypeError: write() argument must be str, not bytes

到达此 tcp 服务器的数据没有写入文件,也没有写入命令行。

错误如下,

Exception in thread Thread-10: Traceback (most recent call last): File "F:\Installation\Anaconda\lib\threading.py", line 916, in _bootstrap_inner self.run() File "", line 25, in run f.write(data) TypeError: write() argument must be str, not bytes

我的代码:

import socket
from threading import Thread
from socketserver import ThreadingMixIn
import time
TCP_IP = '192.168.0.159'
TCP_PORT = 9001
BUFFER_SIZE = 1024

class ClientThread(Thread):
    def __init__(self,ip,port,sock):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.sock = sock
        print(" New thread started for "+ip+":"+str(port))

    def run(self):
        filename='ble_scan.txt'
        f = open(filename,'w')
        while True:
            data=self.sock.recv(BUFFER_SIZE)
            print((data))
            f.write(data)
            f.close()
            self.sock.close()
            break

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
    tcpsock.listen(5)
    print("Waiting for incoming connections...")
    (conn, (ip,port)) = tcpsock.accept()
    print('Got connection from ', (ip,port))
    newthread = ClientThread(ip,port,conn)
    newthread.start()
    threads.append(newthread)
for t in threads:
    t.join()

测试这个 f = open(filename,'w') 或这个 f = open(filename,'a') 而不是 f = open(filename,'wb')

import socket
from threading import Thread
from socketserver import ThreadingMixIn
import time
TCP_IP = '192.168.0.159'
TCP_PORT = 9001
BUFFER_SIZE = 1024


class ClientThread(Thread):


    def __init__(self, ip, port, sock):
        Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.sock = sock
        print(" New thread started for "+ip+":"+str(port))


    def run(self):
        filename = 'ble_scan.txt'
        f = open(filename, 'w')
        while True:
            data = self.sock.recv(BUFFER_SIZE)
            print((data))
            f.write(data)
            f.close()
            self.sock.close()
            break


tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpsock.bind((TCP_IP, TCP_PORT))
threads = []
while True:
    tcpsock.listen(5)
    print("Waiting for incoming connections...")
    (conn, (ip, port)) = tcpsock.accept()
    print('Got connection from ', (ip, port))
    newthread = ClientThread(ip, port, conn)
    newthread.start()
    threads.append(newthread)
for t in threads:
    t.join()