需要在tcp s中添加计时器线程

2024-04-20 03:52:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使tcp服务器双向。 我想添加一个计时器线程,并发送数据后,每10秒到所有客户端。你知道吗

我的代码如下

import socket
import sys
from thread import *

HOST = '192.168.137.130'   # Symbolic name meaning all available interfaces
PORT = 8888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
    print data
    print 'rcv data:'
        #reply = 'OK...' + data
        if not data: 
            break

        conn.sendall('hello')

    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()

我曾尝试在while循环中添加一些代码,但无法实现,因为循环只有在有新连接或客户端向服务器发送数据时才处于活动状态。你知道吗


Tags: andthetoimportclientdatanotfunction