By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,137 Members | 2,199 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,137 IT Pros & Developers. It's quick & easy.

TCP Listen port with multiple connections

P: n/a
Hello everyone,
I have this code for TCPListenPort. The code works fine, but my manager is
asking me to establish multiple connections to the same port. How can i
acheive that

below is my code

Int32 port = Int32.Parse(ConfigurationManager.AppSettings["port"]);

IPAddress localAddr =
IPAddress.Parse(ConfigurationManager.AppSettings["IpAddress"]);
TcpListener server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;

// Enter the listening loop.
while (true)
{
// Perform a blocking call to accept requests.
TcpClient client = server.AcceptTcpClient();
remotePoint = client.Client.RemoteEndPoint.ToString();
data = null;
NetworkStream stream = client.GetStream();
int i;

// Loop to receive all the data sent by the clie nt.
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);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg =
System.Text.Encoding.ASCII.GetBytes(data);
if (msg.Length 5)
{

byte[] msgClone =
writeClassLibrary.getReturnBytes.ReturnData(_sessi onDisplay, msg);
stream.Write(msgClone, 0, msgClone.Length);
}

}
// Shutdown and end connection
client.Close();
}

Oct 5 '07 #1
Share this Question
Share on Google+
15 Replies


P: n/a
Vinki wrote:
I have this code for TCPListenPort. The code works fine, but my manager is
asking me to establish multiple connections to the same port. How can i
acheive that
IMHO, the most straightforward way would be to use the async methods for
the TcpClient, so that you don't have to do the processing in the loop.
It's that processing that prevents you from dealing with a new client
until you're completely done with the current one.

If you wanted to make the code really nice, you could make the
TcpListener use the async methods as well. Then none of this code would
have to exist in a specific thread.

Pete
Oct 5 '07 #2

P: n/a
can you point me to any example code for async method.

Thanks

"Peter Duniho" wrote:
Vinki wrote:
I have this code for TCPListenPort. The code works fine, but my manager is
asking me to establish multiple connections to the same port. How can i
acheive that

IMHO, the most straightforward way would be to use the async methods for
the TcpClient, so that you don't have to do the processing in the loop.
It's that processing that prevents you from dealing with a new client
until you're completely done with the current one.

If you wanted to make the code really nice, you could make the
TcpListener use the async methods as well. Then none of this code would
have to exist in a specific thread.

Pete
Oct 6 '07 #3

P: n/a
Are you mentioning to something like this

http://msdn2.microsoft.com/en-us/lib...et(VS.80).aspx

"Peter Duniho" wrote:
Vinki wrote:
I have this code for TCPListenPort. The code works fine, but my manager is
asking me to establish multiple connections to the same port. How can i
acheive that

IMHO, the most straightforward way would be to use the async methods for
the TcpClient, so that you don't have to do the processing in the loop.
It's that processing that prevents you from dealing with a new client
until you're completely done with the current one.

If you wanted to make the code really nice, you could make the
TcpListener use the async methods as well. Then none of this code would
have to exist in a specific thread.

Pete
Oct 6 '07 #4

P: n/a
Vinki wrote:
can you point me to any example code for async method.
Here's a decent starting point:
http://msdn2.microsoft.com/en-us/lib...beginread.aspx

Here's a sample program that does async i/o:
http://msdn2.microsoft.com/en-us/library/kztecsys.aspx
Oct 6 '07 #5

P: n/a
Vinki wrote:
Are you mentioning to something like this

http://msdn2.microsoft.com/en-us/lib...et(VS.80).aspx
Yes, that would be what you'd use for TcpListener. For TcpClient, you
need to use the async i/o methods for the Stream class, but they work in
a very similar way.
Oct 6 '07 #6

P: n/a
Hi Peter,

Do you have any example for this to do both TCListener and IO stream part.
I will really appreacite if you can email me or paste an example.

Thanks.
email: av*************@yahoo.com

"Peter Duniho" wrote:
Vinki wrote:
Are you mentioning to something like this

http://msdn2.microsoft.com/en-us/lib...et(VS.80).aspx

Yes, that would be what you'd use for TcpListener. For TcpClient, you
need to use the async i/o methods for the Stream class, but they work in
a very similar way.
Oct 6 '07 #7

P: n/a
I wrote this after following that microsoft code. This complies succesfully.
I was wondering where in this code will I get the data coming from client. In
my earlier code, I had this

data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

below is the new code

private void Form1_Load(object sender, EventArgs e)
{
Int32 port = 9007;
IPAddress localAddr = IPAddress.Parse(IPAddress);
TcpListener server = null;
server = new TcpListener(localAddr, port);
server.Start();
DoBeginAcceptSocket(server);
}

// Thread signal.
public static ManualResetEvent clientConnected =
new ManualResetEvent(false);

// Accept one client connection asynchronously.
public static void DoBeginAcceptSocket(TcpListener listener)
{
// Set the event to nonsignaled state.
clientConnected.Reset();

// Start to listen for connections from a client.
Console.WriteLine("Waiting for a connection...");

// Accept the connection.
// BeginAcceptSocket() creates the accepted socket.
listener.BeginAcceptSocket(
new AsyncCallback(DoAcceptSocketCallback), listener);
// Wait until a connection is made and processed before
// continuing.
clientConnected.WaitOne();
}

// Process the client connection.
public static void DoAcceptSocketCallback(IAsyncResult ar)
{
// Get the listener that handles the client request.
TcpListener listener = (TcpListener)ar.AsyncState;

// End the operation and display the received data on the
//console.
Socket clientSocket = listener.EndAcceptSocket(ar);

// Process the connection here. (Add the client to a
// server table, read data, etc.)
Console.WriteLine("Client connected completed");

// Signal the calling thread to continue.
clientConnected.Set();
}
}

"Peter Duniho" wrote:
Vinki wrote:
Are you mentioning to something like this

http://msdn2.microsoft.com/en-us/lib...et(VS.80).aspx

Yes, that would be what you'd use for TcpListener. For TcpClient, you
need to use the async i/o methods for the Stream class, but they work in
a very similar way.
Oct 6 '07 #8

P: n/a
Vinki wrote:
I wrote this after following that microsoft code. This complies succesfully.
I was wondering where in this code will I get the data coming from client.
In your DoAcceptSocketCallback() method, you would get the Stream from
the TcpClient and use the Stream.BeginRead() method on that. Then in
the callback for that, you'll do the Encoder.GetString() from the bytes
that are received.

Personally, I would use TcpListener.BeginAcceptTcpClient() instead of
BeginAcceptSocket(), since your original code was based on the TcpClient
rather than the Socket.

If you do plan on using the Socket, I would not bother using TcpListener
and TcpClient at all; the Socket API isn't actually all that complicated
and if that's what you're going to use for i/o in the end anyway, you
might as well only use that class. But IMHO your previous code using
TcpClient should be fine, and there's nothing wrong with sticking with that.

Pete
Oct 6 '07 #9

P: n/a
Hi Peter,

I want to stick with that code too, but I don't know how to use async
method for TCPClient. I tried to follow the link that you pasted here, but I
couldn't understand how to integrate that code with my code . I would
appreacite if you have some code written like this that uses async IO stream
and TCP Listener. I will follow that code.

Thanks.

"Peter Duniho" wrote:
Vinki wrote:
I wrote this after following that microsoft code. This complies succesfully.
I was wondering where in this code will I get the data coming from client.

In your DoAcceptSocketCallback() method, you would get the Stream from
the TcpClient and use the Stream.BeginRead() method on that. Then in
the callback for that, you'll do the Encoder.GetString() from the bytes
that are received.

Personally, I would use TcpListener.BeginAcceptTcpClient() instead of
BeginAcceptSocket(), since your original code was based on the TcpClient
rather than the Socket.

If you do plan on using the Socket, I would not bother using TcpListener
and TcpClient at all; the Socket API isn't actually all that complicated
and if that's what you're going to use for i/o in the end anyway, you
might as well only use that class. But IMHO your previous code using
TcpClient should be fine, and there's nothing wrong with sticking with that.

Pete
Oct 6 '07 #10

P: n/a
Hi Peter,

I think you posted something, but I cannot see any message. It mentions
your name at the bottom of all the message, but I cannot see the message
itself.

"Vinki" wrote:
Hi Peter,

I want to stick with that code too, but I don't know how to use async
method for TCPClient. I tried to follow the link that you pasted here, but I
couldn't understand how to integrate that code with my code . I would
appreacite if you have some code written like this that uses async IO stream
and TCP Listener. I will follow that code.

Thanks.

"Peter Duniho" wrote:
Vinki wrote:
I wrote this after following that microsoft code. This complies succesfully.
I was wondering where in this code will I get the data coming from client.
In your DoAcceptSocketCallback() method, you would get the Stream from
the TcpClient and use the Stream.BeginRead() method on that. Then in
the callback for that, you'll do the Encoder.GetString() from the bytes
that are received.

Personally, I would use TcpListener.BeginAcceptTcpClient() instead of
BeginAcceptSocket(), since your original code was based on the TcpClient
rather than the Socket.

If you do plan on using the Socket, I would not bother using TcpListener
and TcpClient at all; the Socket API isn't actually all that complicated
and if that's what you're going to use for i/o in the end anyway, you
might as well only use that class. But IMHO your previous code using
TcpClient should be fine, and there's nothing wrong with sticking with that.

Pete
Oct 6 '07 #11

P: n/a
Vinki wrote:
Hi Peter,

I think you posted something, but I cannot see any message. It mentions
your name at the bottom of all the message, but I cannot see the message
itself.
Well, as a start you may want to consider using a real newsreader to
access this newsgroup, rather than going through Microsoft's web
interface. I've never actually had problems with it myself, but it's
not hard to imagine it screwing up now and then and not displaying posts
correct.

That said, I didn't post any code (yet). I will type in something quick
and dirty, in reply to your other message. Sorry I don't have time for
anything more elaborate at the moment.

Pete
Oct 6 '07 #12

P: n/a
Vinki wrote:
Hi Peter,

Thanks for writing a sample code. I did exactly you mentioned. Below is
the code. I guess I am doing something wrong. The code terminates at this
point

server.BeginAcceptTcpClient(AcceptCallback, server);
Yes, of course it does. You don't have anything to prevent it from
exiting the Main() method, which is what defines exiting a console
application.

Note that the code you posted previously specified that you were
starting the server in a form's Load event handler. Had you used my
code in that context, there wouldn't be a problem.

If you want to do a console application, you'll need to make the Main()
method wait until it's time to exit. How you will define that, I don't
know. It's up to you. One possibility would be to have a WaitHandle
that the Main() method waits on. Then your application would take input
from somewhere else (maybe from one of the client's connected to it, by
having the client send a special command, but there are lots of other
alternatives), and when that input indicated the application should
exit, it could set the WaitHandle.

That's the simple description. In reality, when it's time to shut down
the application, you'd want to shutdown and close the open clients and
the server before exiting. But first things first. :)

Pete
Oct 7 '07 #13

P: n/a
Hi Peter,

I will write this code inside a window service. In on start event of the
window service. I haven't created the service yet, but I was wondering will
window service be OK fo this code. Can you please advice on that. I already
took lot of your time, but just one more question the code that you helped me
to write. Does this part looks fine to you because I was little bit confused
in the last part. Below is the code. I also pasted the whole code in my last
post.

if (cbRead == 0)
{
// The client has closed the connection
return;
}
else
{
state.client.GetStream().BeginRead(state.buffer,
0,state.buffer.Length, ReadCallback, state);

}
}
"Peter Duniho" wrote:
Vinki wrote:
Hi Peter,

Thanks for writing a sample code. I did exactly you mentioned. Below is
the code. I guess I am doing something wrong. The code terminates at this
point

server.BeginAcceptTcpClient(AcceptCallback, server);

Yes, of course it does. You don't have anything to prevent it from
exiting the Main() method, which is what defines exiting a console
application.

Note that the code you posted previously specified that you were
starting the server in a form's Load event handler. Had you used my
code in that context, there wouldn't be a problem.

If you want to do a console application, you'll need to make the Main()
method wait until it's time to exit. How you will define that, I don't
know. It's up to you. One possibility would be to have a WaitHandle
that the Main() method waits on. Then your application would take input
from somewhere else (maybe from one of the client's connected to it, by
having the client send a special command, but there are lots of other
alternatives), and when that input indicated the application should
exit, it could set the WaitHandle.

That's the simple description. In reality, when it's time to shut down
the application, you'd want to shutdown and close the open clients and
the server before exiting. But first things first. :)

Pete
Oct 7 '07 #14

P: n/a
Vinki wrote:
Hi Peter,

I will write this code inside a window service. In on start event of the
window service. I haven't created the service yet, but I was wondering will
window service be OK fo this code. Can you please advice on that.
There's nothing special about a service that would prevent the same i/o
code from working. You still have to keep your process from exiting,
but that's true for _any_ application that you want to continue running.
It's not unique to network i/o.
I already
took lot of your time, but just one more question the code that you helped me
to write. Does this part looks fine to you because I was little bit confused
in the last part. Below is the code. I also pasted the whole code in my last
post.

if (cbRead == 0)
{
// The client has closed the connection
return;
}
else
{
state.client.GetStream().BeginRead(state.buffer,
0,state.buffer.Length, ReadCallback, state);

}
}
I would either make the "true" block of the if() statement return
directly, or I would have the "else" statement. I wouldn't have both;
it's not harmful to have both, but it would be redundant.

Either:

if(...)
{
// do something
return;
}

// do something else

Or:

if(...)
{
// do something
}
else
{
// do something else
}

Which one you'd use just depends on your personal preference. Me, I
tend to prefer _not_ to have more than one point of return in my
methods, and I prefer not to have any gotos. However, this is balanced
by my preference to not have my code repeatedly indented. So where
there's a very simple flow of logic like the above, I don't mind
sticking an extra return statement in, as in the first example.

But if you do that, you don't need the "else" statement. You can just
put the "else" code after the whole if() statement; having the return
statement in the "true" block of the if() statement ensures that you
will only execute the code that follows if the condition in the if()
statement is false. Thus, the "else" statement in that case is superfluous.

Pete
Oct 7 '07 #15

P: n/a
Vinki wrote:
I have this code for TCPListenPort. The code works fine, but my manager is
asking me to establish multiple connections to the same port. How can i
acheive that
If the number of concurrent connections are not too big, then the
simple one thread per connection approach will work fine.

Arne
Oct 8 '07 #16

This discussion thread is closed

Replies have been disabled for this discussion.