| | |
Socket programming with a service
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved |
•
•
Join Date: Jan 2008
Posts: 18
Reputation:
Solved Threads: 0
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
Thanks in advance
•
•
Join Date: Jun 2008
Posts: 128
Reputation:
Solved Threads: 31
Have you checked the firewall?
Try open the server port higher (>5000).
Check out if minimal implementations are working.
Try open the server port higher (>5000).
Check out if minimal implementations are working.
•
•
Join Date: Jan 2008
Posts: 18
Reputation:
Solved Threads: 0
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
service_module.py is imported in the following code. This code is the serviceLauncher.py... This function is sent to py2exe for compiling.
Here is the client code...
I hope this helps... thanks for the help
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
Python Syntax (Toggle Plain Text)
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 try: response = 'Server got: ' + data except: 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 connection.close() 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): sys.exit() time.sleep(0.3) 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.
Python Syntax (Toggle Plain Text)
import win32serviceutil import win32service import win32event import os import sys import time, redirect sys.stopdriver = "false" def main(): ''' Modulo principal para windows ''' sys.path.insert(0,os.getcwd()) 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): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) sys.stopservice = "true" win32event.SetEvent(self.hWaitStop) 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...
Python Syntax (Toggle Plain Text)
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
![]() |
Similar Threads
- Socket Programming... (C#)
- About socket programming in php (PHP)
- Socket Programming (C++)
- Socket Programming (ASP.NET)
- C++ socket programming (C++)
- Socket programming + porting Unix to Win32 (C)
Other Threads in the Python Forum
- Previous Thread: What is this code missing?
- Next Thread: Web Spider Help
| Thread Tools | Search this Thread |
Tag cloud for Python
abrupt ansi anti approximation array assignment backend basic beginner binary bluetooth builtin calculator character chmod code converter countpasswordentry curved customdialog dan08 dictionaries dictionary drive dynamic examples excel exe file float format ftp function graphics gui heads homework ideas import input java launcher line linux list lists loop mouse mysqlquery newb number numbers output parsing path plugin pointer port prime program programming progressbar projects py2exe pygame pyqt pysimplewizard python random recursion recursive refresh scrolledtext ssh stamp statistics string strings sum table terminal text textarea thread threading time tkinter tlapse tricks tuple tutorial twoup ubuntu unicode urllib urllib2 variable windows write wxpython






