Reputation: 1195
C# .NET 4.5 Visual Studio 2010
This is more of a thought exercise than proof-reading my code.
I am working on developing an HTTP listener that runs as a service in Windows. I made a standalone Windows Forms project using the below code and it works fine. Every time a request came in I was able to make a message box appear that showed the body of the HTTP POST Request.
The problem is that the same code, when copied into a background service DLL project, doesn't "catch" the HTTP requests that are sent to it. This apparent in the log file I use to debug (see the calls to Log.Write()
in the code below).
I am running this all on the same PC, so I don't think the issue is that the port is in use, or that I am using the wrong IP.
I am wondering if the HTTP listener doesn't work because it's a background service, or maybe because it's a DLL.
IP address below changed to 1.2.3.4 for security reasons.
class http_listener
{
bool _stop;
main ()
{
_stop = false;
// start ListenForEvents() in new thread
// [code omitted]
}
private void ListenForEvents(object o)
{
Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse("1.2.3.4");
System.Net.EndPoint endPoint = new System.Net.IPEndPoint(ipAddress, 8000);
_socket.Bind(endPoint);
_socket.Listen(1000);
while (!_stop)
{
Log.Write("this IS written to log every 2 seconds");
Thread.Sleep(2000);
_recvBufSize = 1000; // max bytes to recieve
_begAcceptResult = _socket.BeginAccept(null, _recvBufSize, new AsyncCallback(RequestCallback), _socket);
}
_eventListenerThread = null;
}
private void RequestCallback(IAsyncResult begAcceptResult)
{
Log.Write("this is NOT written to log");
Socket socket = (Socket)begAcceptResult.AsyncState;
byte[] buf;
int bytesTransferred;
Socket endSocket = socket.EndAccept(out buf, out bytesTransferred, begAcceptResult);
string stringTransferred = Encoding.ASCII.GetString(buf, 0, bytesTransferred);
Log.Write(stringTransferred);
}
}
Upvotes: 0
Views: 841
Reputation: 1195
Got it working. For some reason the port I wanted to use was blocked by Windows Firewall when I ran my server as a service, but it did not block it when I ran the server as a Forms application. The service had an exception listed in the Firewall settings, but the exception only allowed communication on one particular port; not the one I wanted to use.
Here is the setting I changed to allow communication on my port:
Control Panel > Windows Firewall > Advanced Settings > Inbound Rules > (right-click name of service) > Properties > "Protocols and Ports" tab > Local port > added 8000 to the port(s) already listed there
Upvotes: 1