Problem with tcp server when converting to service
- by djerry
Hello lads,
I'm working on monitoring some object (cdr-packets). I'm setting up a tcp-server and am listening on port 50043 for the packages. The program as a console application is working just fine, my server is working like it should and i'm receiving the packets. When i try to use it as a service, i cannot seem to get a client connected to my server. Is there something i need to change to deploy this as a service? Code below is from my application:
this is my service class where i start
protected override void OnStart(string[] args)
{
server = new TcpServer();
server.StartServer();
}
this is the constructor of TcpServer
public TcpServer()
{
try
{
_server = new TcpListener(IPAddress.Any, 50043);
}
catch (Exception)
{
_server = null;
}
}
this is the method i call after initialising the class
public void StartServer()
{
if (_server != null)
{
// Create a ArrayList for storing SocketListeners before starting the server.
_socketListenersList = new ArrayList();
// Start the Server and start the thread to listen client requests.
_server.Start();
_serverThread = new Thread(new ThreadStart(ServerThreadStart));
_serverThread.Start();
// Create a low priority thread that checks and deletes client
// SocktConnection objcts that are marked for deletion.
_purgingThread = new Thread(new ThreadStart(PurgingThreadStart));
_purgingThread.Priority = ThreadPriority.Lowest;
_purgingThread.Start();
}
}
this is the thread that keep checking if any client tries to connect
private void ServerThreadStart()
{
// Client Socket variable;
Socket clientSocket = null;
TcpSocketListener socketListener = null;
while (!_stopServer)
{
try
{
// Wait for any client requests and if there is any request from any
//client accept it (Wait indefinitely).
clientSocket = _server.AcceptSocket();
// Create a SocketListener object for the client.
socketListener = new TcpSocketListener(clientSocket);
// Add the socket listener to an array list in a thread safe fashon.
lock (_socketListenersList)
{
_socketListenersList.Add(socketListener);
}
// Start a communicating with the client in a different thread.
socketListener.StartSocketListener();
}
catch (SocketException se)
{
_stopServer = true;
}
}
}
when for the first time a packet waits to be read, and i get to "clientSocket = _server.AcceptSocket();", it throws an exception (service, not very good debugable)
Does anyone recognize this problem or can help me?
Thanks in advance