问题
I'm developing a webservice that will, when called, notify another program via a tcp connection. My problem is where to store the open tcp connection. The way I understand web services, they start and end with each HTTP Request, with no room for application wide variables, like the open tcp connection.
Please correct me if I'm wrong.
Specifically, in what part of the asmx file, or outside of it, should I place the code for listening for incoming tcp traffic?
回答1:
You can place the tcp connection as a static member of the service class and make a static constructor that handles the instantiation.
This will create the tcp connection before the first access of the web service is handled and then persist the connection as long as the hosting process is running. The only drawback with that approach is that the tcp connection is process wide. If you host two instances of the web service within the same process (quite unlikely) they will share the same tcp connection.
回答2:
Application events in Global.asax should fire for a web service hosted as an application in IIS. You can use these. Keep in mind that they will fire even if a web page and not the web service is accessed in the same application.
回答3:
Fortunately for you, you are wrong.
Application-wide events do fire plus you have the access to all asp.net containers, the Application
container for application-level variables, the Session
container for session-level variables (if the client side supports cookies, the session id could even be passed in a cookie) and the Items
container for request-level variables.
However, whether or not this helps you to store an additional tcp listener (if I understand correcly) is another story, not obvious one.
来源:https://stackoverflow.com/questions/9054234/does-an-asp-net-webservice-have-something-like-application-start-and-application