python中的套接字只会发送它收到的数据

时间:2010-07-09 21:06:12

标签: python sockets

我必须在代码中遗漏一些东西。我已经重写了一个'echo server'示例,以便在收到某些内容时做更多的事情。

目前的情况如下:


#!/usr/bin/env python

import select
import socket
import sys
import threading
import time
import Queue

globuser = {}
queue = Queue.Queue()

class Server:
    def __init__(self):
        self.host = ''
        self.port = 2000
        self.backlog = 5
        self.size = 1024
        self.server = None
        self.threads = []

    def open_socket(self):
        try:
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server.bind((self.host,self.port))
            self.server.listen(5)
        except socket.error, (value,message):
            if self.server:
                self.server.close()
            print "Could not open socket: " + message
            sys.exit(1)

    def run(self):
        self.open_socket()
        input = [self.server,sys.stdin]
        running = 1
        while running:
            inputready,outputready,exceptready = select.select(input,[],[])

            for s in inputready:

                if s == self.server:
                    # handle the server socket
                    c = Client(self.server.accept(), queue)
                    c.start()
                    self.threads.append(c)

                elif s == sys.stdin:
                    # handle standard input
                    junk = sys.stdin.readline()
                    running = 0

        # close all threads

        self.server.close()
        for c in self.threads:
            c.join()

class Client(threading.Thread):
    initialized=0

    def __init__(self,(client,address), queue):
        threading.Thread.__init__(self)
        self.client = client
        self.address = address
        self.size = 1024
    self.queue = queue
    self.threads = []
        global globuser
        print 'Client thread created!'


    def run(self):
        running = 1
        while running:
            print 'While running client'
            data = self.client.recv(self.size)
            print 'Dit we receive data?'
            if data:
                print 'Data received!'
        print 'Fetching data from socket: ',
        if data[0] == 'I':
            print 'Initializing user: ' + data
            user = {'uid': data[1:6] ,'x': data[6:9], 'y': data[9:12]}
            globuser[user['uid']] = user
            print globuser
            initialized=1
            m=updateClient(user['uid'], queue)
            m.start()
            self.threads.append(m)
            self.client.send('Beginning - Initialized'+';')

        elif data[0] == 'A':
            print 'Client has received previous data: ' + data

        #On deactivation, nothing works.
                self.client.send(data+';')
                #print 'Client Data sent: ' + data
            else:
                print 'Closing'
                self.client.close()
                running = 0

    if self.queue.empty():
        print 'Queue is empty'
    else:
        print 'Queue has information: ',
        data2 = self.queue.get(1, 1)
        isdata2 = 1
        if data2 == 'Exit':
            running = 0
            print 'Client is being closed'
            self.client.close()

    if isdata2 == 1:
        print 'Sending data to client: ' + data2,
        self.client.send(data2)
        self.queue.task_done()
        isdata2 = 0

    time.sleep(1)

class updateClient(threading.Thread):

    def __init__(self,uid, queue):
        threading.Thread.__init__(self)
        self.uid = uid
        self.queue = queue
        global globuser
        print 'updateClient thread started!'

    def run(self):
        running = 20
        test=0
        while running > 0:
            test = test + 1
            self.queue.put('Test Queue Data #' + str(test))
            running = running - 1
            time.sleep(1)

        print 'Updateclient has stopped'



if __name__ == "__main__":
    s = Server()
    s.run() 

这样运行正常,但是继续将相同数据与其他数据一起发回是一种愚蠢的行为。

在代码中间你会看到


        #On deactivation, nothing works.
                self.client.send(data+';')
                #print 'Client Data sent: ' + data

当我取消self.client.send(data+';')或将其更改为self.client.send('something else;')时,它不起作用!客户端什么都没收到。

“数据”变量有什么特别之处吗?我需要以某种方式格式化字符串吗?

1 个答案:

答案 0 :(得分:2)

这是一个清理过的功能版代码!我自己测试过,虽然我没有编写单元测试。

有一些语法错误和其他杂项问题 原始代码,所以我采取了一些自由。我假设协议是 通过使用;作为分隔符进行框架,因为在每个分节结束时都会发送; 向客户端发送消息,但原始代码中没有进行任何框架。

from twisted.internet import reactor, protocol, task
from twisted.protocols import basic
from twisted.python import log
import sys

class ServerProtocol(basic.LineOnlyReceiver):
    delimiter = ';'

    def lineReceived(self, line):
        if line.startswith('I'):
            user = dict(uid=line[1:6], x=line[6:9], y=line[9:12])
            self.factory.users[user['uid']] = user
            log.msg(repr(self.factory.users))
            self.startUpdateClient()
            self.sendLine('Beginning - Initialized')
        elif line.startswith('A'):
            self.sendLine(line)
        else:
            self.transport.loseConnection()

    def _updateClient(self):
        if self._running == 0:
            self._looper.stop()
            return
        self._running -= 1
        self._test += 1
        self.sendLine('Test Queue Data #%d' % (self._test,))

    def startUpdateClient(self):
        self._running, self._test = 20, 0
        self._looper = task.LoopingCall(self._updateClient)
        self._looper.start(1, now=False)

class Server(protocol.ServerFactory):
    protocol = ServerProtocol
    def __init__(self):
        self.users = {}

if __name__ == '__main__':
    log.startLogging(sys.stderr)
    reactor.listenTCP(2000, Server())
    reactor.run()