473,386 Members | 1,908 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

TCP Listen port with multiple connections

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
15 20598
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: ss | last post by:
Dear All, I use ODBC to connect php (installed on linux) to a MS SQL Server 2000 database. I use iODBC and Freetds. Everything looks fine, until I try to open a multiple connection at once...
1
by: Jim Kipp | last post by:
Hi I am writing a simple server to monitor ports. The problem is I don't know how to make it listen on multiple ports. It creates the first socket, listens, than accepts and of course the accept...
8
by: James Baker | last post by:
I've been using ASP.NET for a couple years now and I'm trying to fall back into ASP for a new position I've acquired...and I'm having a bit of trouble remembering. I'm running to a problem where...
1
by: billiejoex | last post by:
Hi all. I noticed that with the original pcap sniffing library it is possible to listen on multiple devices by using "select()" or "poll()" function. These function aren't present in pcapy module....
7
by: Sharon | last post by:
Hi all, I've implemented a TCP server using the Socket async methods. When connecting to the server from 3 instances of hyper terminal, i've noticed that each of the newly created server sockets,...
0
by: Yelena Varshal | last post by:
Hello, I am using ODBC to access Microsoft Access database. I use just generic ADO code. I don't have problems opening multiple connections from the same page on the development server but the...
1
by: Yelena Varshal via AccessMonster.com | last post by:
Hello, What are the pre-requisites / conditions for the ability to create multiple connections to MS ACCESS database and what is the precedence of its application? adModeShareDenyNone in the code,...
1
by: BF | last post by:
Hi, I want the change the SQL listen port of a named 2005 sql instance. Is there a way I can run an sql query against the named instance which gives me back which registry setting I need to...
0
by: mcosgriff | last post by:
Using Visual Studio 2005, language is C# What I did so far was add a web reference, with this I can listen to a web service and receive an XML file with updated data and store relevant data off to...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.