473,583 Members | 3,382 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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(Con figurationManag er.AppSettings["port"]);

IPAddress localAddr =
IPAddress.Parse (ConfigurationM anager.AppSetti ngs["IpAddress"]);
TcpListener server = new TcpListener(loc alAddr, 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.AcceptTc pClient();
remotePoint = client.Client.R emoteEndPoint.T oString();
data = null;
NetworkStream stream = client.GetStrea m();
int i;

// Loop to receive all the data sent by the clie nt.
while ((i = stream.Read(byt es, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Enc oding.ASCII.Get String(bytes,
0, i);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg =
System.Text.Enc oding.ASCII.Get Bytes(data);
if (msg.Length 5)
{

byte[] msgClone =
writeClassLibra ry.getReturnByt es.ReturnData(_ sessionDisplay, msg);
stream.Write(ms gClone, 0, msgClone.Length );
}

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

Oct 5 '07 #1
15 20682
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.Enc oding.ASCII.Get String(bytes, 0, i);
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(data);

below is the new code

private void Form1_Load(obje ct sender, EventArgs e)
{
Int32 port = 9007;
IPAddress localAddr = IPAddress.Parse (IPAddress);
TcpListener server = null;
server = new TcpListener(loc alAddr, port);
server.Start();
DoBeginAcceptSo cket(server);
}

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

// Accept one client connection asynchronously.
public static void DoBeginAcceptSo cket(TcpListene r listener)
{
// Set the event to nonsignaled state.
clientConnected .Reset();

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

// Accept the connection.
// BeginAcceptSock et() creates the accepted socket.
listener.BeginA cceptSocket(
new AsyncCallback(D oAcceptSocketCa llback), listener);
// Wait until a connection is made and processed before
// continuing.
clientConnected .WaitOne();
}

// Process the client connection.
public static void DoAcceptSocketC allback(IAsyncR esult 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.EndAcc eptSocket(ar);

// Process the connection here. (Add the client to a
// server table, read data, etc.)
Console.WriteLi ne("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 DoAcceptSocketC allback() method, you would get the Stream from
the TcpClient and use the Stream.BeginRea d() method on that. Then in
the callback for that, you'll do the Encoder.GetStri ng() from the bytes
that are received.

Personally, I would use TcpListener.Beg inAcceptTcpClie nt() instead of
BeginAcceptSock et(), 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 DoAcceptSocketC allback() method, you would get the Stream from
the TcpClient and use the Stream.BeginRea d() method on that. Then in
the callback for that, you'll do the Encoder.GetStri ng() from the bytes
that are received.

Personally, I would use TcpListener.Beg inAcceptTcpClie nt() instead of
BeginAcceptSock et(), 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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2020
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 to the SQL server (I didn't close a connection before I opened a new one). I've got an error with strange characters : Warning: SQL error: ä , SQL...
1
4834
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 call blocks, so it does not return to create socket for the other ports. I am doing this in windows, so using 'fcntl' to do non blocking won't work....
8
2009
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 the basic logic is as follows: Query Do While Not rs.EOF Query based on value in rs Another query based on value in rs Loop
1
2507
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. Do you got any suggestion to avoid this problem?
7
7550
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, uses the same server port. I assumed that a new connection will receive a unique port. If this is the way its suppose to work, is it a performance...
0
2206
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 same code does not work on the production server and on my Windows XP workstation running IIS. One connection opens fine on the production server and...
1
5318
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, Exclusive checkbox in the ODBC source, Tools->Options->Advanced->Shared in the Database Options, what else? I have a problem when multiple...
1
2655
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 use. so MSSQL.1 MSSQL.2 or MSSQL.3 Or is there another way I can set the listenport through script or
0
1191
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 a database. What I am trying to do use the same web reference I added but change the url connection string and listen to multiple web services. ...
0
7894
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7821
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8172
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7929
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8190
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5697
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5370
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
1424
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1152
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.