TCPClient App Question

F

Frank

I wonder if anyone could give me a suggestion on how to best handle this
scenario.

I wish to have an aspx page contact a server and receive messages.
Initially, a login messge is sent, then after being validated, a second
message is sent which contains data to complete a stock market trade. The
server then should respond not only once, but with several return messages.

So far all I have found are examples that send, receive, and disconnect,
which I have working. However, since all returning data to the client should
be in response to the order submitted, I cannot simply continue to resend
the original data for the trade. I need to keep the connection open and the
grab all incoming messages until the client quits.

Could anyone suggest how I should modfy the following code to keep the
connection open and continue to rceive subsequent messages?



static void Connect(String server, String message)
{
try
{
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
Int32 port = 13000;
TcpClient client = new TcpClient(server, port);

// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

// Get a client stream for reading and writing.
// Stream stream = client.GetStream();

NetworkStream stream = client.GetStream();

// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);

Console.WriteLine("Sent: {0}", message);

// Receive the TcpServer.response.

// Buffer to store the response bytes.
data = new Byte[256];

// String to store the response ASCII representation.
String responseData = String.Empty;

// Read the first batch of the TcpServer response bytes.
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);

// Close everything.
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}

Console.WriteLine("\n Press Enter to continue...");
Console.Read();
}
 
T

tdavisjr

try doing something like this:

while(true)
{

NetworkStream stream = client.GetStream();
....
....
....

Console.WriteLine("Received: {0}", responseData);

}

client.Close();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,705
Latest member
Stefkari24

Latest Threads

Top