how to multithread on a python server
- by user3732790
HELP please i have this code
import socket
from threading import *
import time
HOST = '' # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
s.bind((HOST, PORT))
print ('Socket bind complete')
s.listen(10)
print ('Socket now listening')
def listen(conn):
odata = ""
end = 'end'
while end == 'end':
data = conn.recv(1024)
if data != odata:
odata = data
print(data)
if data == b'end':
end = ""
print("conection ended")
conn.close()
while True:
time.sleep(1)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
Thread.start_new_thread(listen,(conn))
and i would like it so that when ever a person comes onto the server it has its own thread. but i can't get it to work please someone help me. :_(
here is the error code:
Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:61475
Traceback (most recent call last):
File "C:\Users\Myles\Desktop\test recever - Copy.py", line 29, in <module>
Thread.start_new_thread(listen,(conn))
AttributeError: type object 'Thread' has no attribute 'start_new_thread'
i am on python version 3.4.0 and here is the users code:
import socket #for sockets
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Socket Created')
host = 'localhost'
port = 8888
remote_ip = socket.gethostbyname( host )
print('Ip address of ' + host + ' is ' + remote_ip)
#Connect to remote server
s.connect((remote_ip , port))
print ('Socket Connected to ' + host + ' on ip ' + remote_ip)
while True:
message = input("> ")
#Set the whole string
s.send(message.encode('utf-8'))
print ('Message send successfully')
data = s.recv(1024)
print(data)
s.close