Re: InterNetwork communication
- From: Jimbo <jimbo@xxxxxxxxxxxxxxxxxxx>
- Date: Thu, 25 Aug 2005 19:27:15 +0000 (UTC)
Benny wrote:
I am rather new to network programming and need a kickstart. I am looking for the same idea as the dos prompt or unix, but remote. I want a client app to be able to send a command to the server and the server respond with an action. I realize i need to use sockets and TcpListner, but my main question: how do i keep the connection alive and listening for any commands until the remote user disconnects? The code i have seen so far just connects sends then disconnects without staying alive. Thanks in advance!
The simple answer is not close the socket at either the client or server until you need to. Your server probably waits for connection like this:
TcpListener listener = new TcpListener(IPAddress.Any, port);
// Start listening for client requests. listener.Start();
while(!Stopping)
{
TcpClient client = listener.AcceptTcpClient();
...
...
}Once you have the TcpClient object from the listener start a separate thread that will process it. In that thread just keep going round the loop of reading the data from the stream and writing the response. Only close the TcpClient object when the listener receives a command like "quit".
The loop might be something like this:
stream = client.GetStream();
Int32 i;
sb = new StringBuilder();
while (!sb.toString().equals("quit")) {
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); sb.Append(data);
}
stream.Write("recieved");
stream.Flush();
}
Your client app will the work on a similar principal of reading and writing to the socket until it sends the the "quit" command, at which point it can close the socket.
Hope this helps. Jimbo .
- Follow-Ups:
- Re: InterNetwork communication
- From: Benny
- Re: InterNetwork communication
- References:
- InterNetwork communication
- From: Benny
- InterNetwork communication
- Prev by Date: Re: confused about .NET 2.0
- Next by Date: Exception when doing CopyTo
- Previous by thread: InterNetwork communication
- Next by thread: Re: InterNetwork communication
- Index(es):
Relevant Pages
|