Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 905335
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T16:12:04+00:00 2026-05-15T16:12:04+00:00

I must be missing something in the code. I’ve rewritten an ‘echo server’ example

  • 0

I must be missing something in the code. I’ve rewritten an ‘echo server’ example to do a bit more when it receives something.

This is how it currently looks:


#!/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() 

This runs fine, although it’s kind of silly to keep sending the same data back again along with other data.

In the middle of the code you’ll see


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

When I DO deactive the self.client.send(data+';') or change it into self.client.send('something else;') it does not work! And the client receives nothing.

Is there something special about the “data” variable? Do I need to format the string in some way?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T16:12:05+00:00Added an answer on May 15, 2026 at 4:12 pm

    Here’s a cleaned-up, functional version of your code! I tested it myself, though I didn’t write unit tests.

    There were some syntax errors and other miscellaneous problems with the
    original code, so I took some liberties. I’m assuming that the protocol is
    framed by using ; as a delimiter, since a ; is sent at the end of every
    message to the client, though no framing was being done in the original code.

    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()
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 530k
  • Answers 530k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer The following overload might give you what you want: String… May 16, 2026 at 11:36 pm
  • Editorial Team
    Editorial Team added an answer The problem is that the 'real' string isn't a string.… May 16, 2026 at 11:36 pm
  • Editorial Team
    Editorial Team added an answer here is a javascript only control that might work... I… May 16, 2026 at 11:36 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Okay, I know I must be missing something obvious here. Here's the sample code
I must be missing something quite obvious here because something rather strange is happening
I must be missing something stupid here but I can not see it. My
I must be missing something obvious here... I can't get .change() to fire on
I must be missing something... So I am in the process of figuring out
I must be missing something really obvious, but for some reason, the command-line version
I must be missing something simple, but I can't see it. First, the setup:
I know I must be missing something, but in a while statement how does
Somewhere in my code I have: class aclass { ... function amethod() { $this->dom
I'm currently messing with google's apis using ajax trough jquery library. In order to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.