Click here to Skip to main content
15,878,677 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
I'm writing an application that has to make a connection on a socket to a set IP and port. During the lifetime of this socket connection, I'm required to listen on a specific port and respond when a message is received on the same port.

The application is part of a complex multi threaded environment, and other threads are running during this process to enable user input.

My Application makes the initial connection on port X, and sends a message.
Starts the 'listener' thread on port Y.
Main execution thread carries on happily.
Once the Application receives a response on port X, the process is over.

Port Y needs to stay open and receive messages and send responses during the life time of port X, however I try and thread the client on port Y it closes itself once a message has been sent.

I've been looking at this for a couple of days, and I can't see a solution!

The listener is started on a seperate thread. Once a connection is made on Port Y, I create a TCPClient to handle the asynchronous call, then in the async method I do my work on a net stream (read and write back). At this point I think I need the netstream to stay open, but the calling thread opens a new stream and closes the existing one! The third party providers have told me the port is being closed by my application, and I can't see how to keep the listener thread netstream open!

Any logical help appreciated, or I'm going to be working over Christmas!!


Updated 19-Dec-13 21:48pm

Without seeing the actual code it's quite difficult to assist.
However will this article help Multi-threaded Client/Server Socket Class[^]?
Share this answer
This sort of sounds like you may be accidentally using the same socket on different ports. Check to make sure each one has his own socket and they're not somehow using the same socket identifier. Also, make sure that your listening thread isn't terminating early for one reason or another.

As Chill60 stated in solution 1, it's hard to give more definitive guidance without any code at all.

Edit: Forgot to mention one thing, in the Windows implementation of sockets (winsock library), if a socket gets deleted/disconnected, the port will close. Make sure you're not deleting/disconnecting the socket by accident.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900