请帮助我有此代码
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))
而且我希望这样,以便每当有人进入服务器时,它都有其自己的线程。但是我无法正常工作,请有人帮助我。:_(这是错误代码:
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'
我在python版本3.4.0上,这是用户代码:
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
您正在使用的API已从thread
移至_thread
,因此您需要这样做;
import _thread
该调用在_thread模块上,并且需要一个元组作为第二个参数,因此启动该线程的正确行应为;
_thread.start_new_thread(listen,(conn,))
恕我直言,threading
尽管您尝试使用它的方向正确,但是该API的工作方式有所不同,因此您必须重写代码才能使其正常工作。例如,可以在此处获得非常简短的描述。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句