I have written a program that is supposed to take a string via a socket connection and echo it back. This program is also run as a service. I can get a client program to connect to the service if the client program is on the same machine as the service, but if I try to connect from another machine, the client program will not connect. Does anyone have any idea about what might be wrong and how to fix it?

Thanks in advance

8 Years
Discussion Span
Last Post by mg0959

Have you checked the firewall?
Try open the server port higher (>5000).

Check out if minimal implementations are working.


Most likely issue is a firewall.

After that there's routers (port forwarding stuff) and proxies. Are you trying to connect over the internet, or on the same subnet?


You can debug this yourself. Try pinging that ip address and port.

Helps to find root cause first


Sorry to be so vague... I will supply the code to clarify.

I don't think there is a problem with firewalls. The program will work if I do not run it as a service, and the error I get on the client side is connection refused.

Here is my code for the service function... called service_module.py

import time
import thread
import os
import sys
from socket import *
from relocator import relocate # this function changes the cwd to the program's physical location

def handleClient(connection):                    # in spawned thread: reply
    print connection, time.ctime()        # show this client's address                  
    data = connection.recv(1024)      # read client socket
        response = 'Server got: ' + data
        sys.stderr.write('\n\nerror in function! ')
        sys.stderr.write("%s, %s\n," % tuple(sys.exc_info()[:2]))
        response = 'There was an error with the server.'
    connection.send(response)  # send a response

class service_test:
    def __init__(self):
        thread.start_new(self.do_something, tuple()) # this is run in a thread so that the service can respond to stop requests
        while True:
                if getattr(sys,'stopservice', False):
    def do_something(self):
        Do something
        myHost = ''                              # server machine, '' means local host
        myPort = 50007                           # listen on a non-reserved port number
        sockobj = socket(AF_INET, SOCK_STREAM)           # make a TCP socket object
        sockobj.bind((myHost, myPort))                   # bind it to server port number
        sockobj.listen(5)                                # allow up to 5 pending connects
        st = '\nIm starting... ' + time.ctime() + '\n'
        print st
        print str(os.getcwd())
        print str(os.path.dirname(sys.argv[0]))
        relocate()          # this just changes the cwd to the program's physical location
        print '\ncwd: '
        print str(os.getcwd())
        print '\n'

        while True:
            connection, address = sockobj.accept()   # pass to thread for service
            print 'Server connected by', address,
            print 'at', time.ctime(), '\n'
            thread.start_new(handleClient, (connection,))

if __name__ == "__main__":
        tst = service_test()

service_module.py is imported in the following code. This code is the serviceLauncher.py... This function is sent to py2exe for compiling.

import win32serviceutil
import win32service
import win32event
import os
import sys
import time, redirect

sys.stopdriver = "false"

def main():
    Modulo principal para windows
    import service_module
    a = service_module.service_test() # this is the funciton from the service_module.py
class ServiceLauncher(win32serviceutil.ServiceFramework):
    _svc_name_ = 'ServiceTest'
    _scv_display_name_ ='ServiceTest'
    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        sys.stopservice = "true"
    def SvcDoRun(self):
        redirect.redirect(main, '')  # this is a stream redirection function...
        # it is run like this for debugging purposes
        # this should not affect anything... I can supply this code too if I need to

Here is the client code...

import sys, os, time
from socket import *              # portable socket interface plus constants
serverHost = 'localhost'          # replaced with the IP address of server prog
serverPort = 50007                # non-reserved port used by the server

message = raw_input('Enter message: ')           # default text to send to server
sockobj = socket(AF_INET, SOCK_STREAM)      # make a TCP/IP socket object
sockobj.connect((serverHost, serverPort))   # connect to server machine and port

sockobj.send(message)# send message to server over socket
data = sockobj.recv(1024)               # receive line from server: up to 1k
print 'Client received:', repr(data)    # make sure it is quoted, was `x`
print 'Client recieved data at',  time.ctime(time.time())
sockobj.close()                             # close socket to send eof to server

raw_input('Press enter when done')

I hope this helps... thanks for the help

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.