ambaliya meera
ambaliya meera

Reputation: 5

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

Data coming to this tcp server is not write into file as well as on command line.

Error is as below,

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

My code:

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()

Upvotes: 0

Views: 813

Answers (1)

waynetech
waynetech

Reputation: 779

test this f = open(filename,'w') or this f = open(filename,'a') instead of 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()

Upvotes: -1

Related Questions