473,386 Members | 1,819 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 listener

Here is my code to create a TCP listener:
file name DataAdapterLauncher.cs
public static TcpListener tcpl;
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 1024);//listen
on all local addresses
tcpl = new TcpListener(ipe);
tcpl.Stop();
tcpl.Start();
and that code handles data:
file name DataAdapterLauncher.cs
private volatile bool monitorPort = true;
byte[] byteReadStream = null; // holds the data in byte buffer
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
}
Please note, I am not a .Net developer, so you might see something strange
in my code.
It does work though but with one problem, as soon as a client disconnects
from my listener, the CPU usage goes up 100% to my exe
and no connections can be made to it.
Any idea?

Thanks for any help.
Jul 18 '08 #1
9 3053
tcpl = new TcpListener(ipe);
tcpl.Stop();
Why the Stop?
tcpl.Start();
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
How do you return to the above line?
If you never do, you can only create one connection

I posted code a time ago about how to get a multi connection server.
This is a part of that thread:
Its very easy, you have a thread just receiving connections in a loop
and
inserting the connections in a queue and then spawning a new thread

while(true)
{
Socket s = listener1.AcceptSocket();
syncedQueue.Enqueue( s );
new Thread( new ThreadStart( workerMethod) ).Start();
}

workerMethod()
{
Socket s = syncedQueue.Dequeue();
}

You have to use a synced queue though:

syncedqueue = Queue.Synchonize( new Queue() );
Jul 18 '08 #2
Like I said, I am not a c# programmer, but I need a little c# code for my
application.
I understand your commens though and will look into it.
But for now it's fine with one connection only however the following
>TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
How do you return to the above line?
If you never do, you can only create one connection
is the reason of CPU going 100% after a client closes connection?

"Ignacio Machin ( .NET/ C# MVP )" <ig************@gmail.comwrote in
message
news:63**********************************@s50g2000 hsb.googlegroups.com...
>
>tcpl = new TcpListener(ipe);
tcpl.Stop();

Why the Stop?
>tcpl.Start();
>TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection

How do you return to the above line?
If you never do, you can only create one connection

I posted code a time ago about how to get a multi connection server.
This is a part of that thread:
Its very easy, you have a thread just receiving connections in a loop
and
inserting the connections in a queue and then spawning a new thread

while(true)
{
Socket s = listener1.AcceptSocket();
syncedQueue.Enqueue( s );
new Thread( new ThreadStart( workerMethod) ).Start();
}

workerMethod()
{
Socket s = syncedQueue.Dequeue();
}

You have to use a synced queue though:

syncedqueue = Queue.Synchonize( new Queue() );

Jul 18 '08 #3
On Jul 18, 3:04*pm, "Markgoldin" <markgoldin_2...@yahoo.comwrote:
Like I said, I am not a *c# programmer, but I need a little c# code formy
application.
I understand your commens though and will look into it.
But for now it's fine with one connection only however the following

*>TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
How do you return to the above line?
If you never do, you can only create one connection

is the reason of CPU going 100% after a client closes connection?
no, of course not, that line is executed AT the connection time, then
you enter in the while loop
do this, copy your code in a win or console project and see where it
gets stuck
Jul 18 '08 #4
On Fri, 18 Jul 2008 11:19:42 -0700, Markgoldin <ma*************@yahoo.com>
wrote:
[...]
It does work though but with one problem, as soon as a client disconnects
from my listener, the CPU usage goes up 100% to my exe
and no connections can be made to it.
Any idea?
Not really. You didn't post a concise-but-complete code sample, so
there's no telling what in your code might be stuck in a loop.

That said, it's certainly possible that the loop you posted for some
reason turns out to be the problem. I admit, from the code you posted
it's not clear why your loop works at all (when would "byteReadStream"
ever _not_ be null?). But assuming there's some condition under which
you're not exiting the loop, it wouldn't surprise me to find that you wind
up consuming 100% CPU, because it's probably a scenario in which no
progress towards exiting the loop is made.

You shouldn't be using the Available property anyway. It's not a reliable
indicator of what you can read. But without a complete code sample, it's
not really possible to offer more detailed advice as to how to fix your
program.

Pete
Jul 18 '08 #5
Here is my modified code:
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
System.Console.WriteLine("In the loop");
}

The change is
System.Console.WriteLine("In the loop");

When I send data to the listener I see "In the loop" two times, after
disconnecting in starts writing "In the loop" without stoping.

Any idea why it gets into the loop after disconnecting?

"Ignacio Machin ( .NET/ C# MVP )" <ig************@gmail.comwrote in
message
news:dd**********************************@a1g2000h sb.googlegroups.com...
On Jul 18, 3:04 pm, "Markgoldin" <markgoldin_2...@yahoo.comwrote:
Like I said, I am not a c# programmer, but I need a little c# code for my
application.
I understand your commens though and will look into it.
But for now it's fine with one connection only however the following
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
How do you return to the above line?
If you never do, you can only create one connection

is the reason of CPU going 100% after a client closes connection?
no, of course not, that line is executed AT the connection time, then
you enter in the while loop
do this, copy your code in a win or console project and see where it
gets stuck
Jul 18 '08 #6
Ok, valid point.

private volatile bool go = true;
private volatile bool monitorPort = true;

byte[] byteReadStream = null;
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
while (go)
{
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
System.Console.WriteLine("In the loop");
}
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(byteReadStream);
monitorPort = true;
}

It works fine as long as a client keeps connection.
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Fri, 18 Jul 2008 11:19:42 -0700, Markgoldin <ma*************@yahoo.com>
wrote:
>[...]
It does work though but with one problem, as soon as a client disconnects
from my listener, the CPU usage goes up 100% to my exe
and no connections can be made to it.
Any idea?

Not really. You didn't post a concise-but-complete code sample, so
there's no telling what in your code might be stuck in a loop.

That said, it's certainly possible that the loop you posted for some
reason turns out to be the problem. I admit, from the code you posted
it's not clear why your loop works at all (when would "byteReadStream"
ever _not_ be null?). But assuming there's some condition under which
you're not exiting the loop, it wouldn't surprise me to find that you wind
up consuming 100% CPU, because it's probably a scenario in which no
progress towards exiting the loop is made.

You shouldn't be using the Available property anyway. It's not a reliable
indicator of what you can read. But without a complete code sample, it's
not really possible to offer more detailed advice as to how to fix your
program.

Pete

Jul 18 '08 #7
On Fri, 18 Jul 2008 13:07:41 -0700, Markgoldin <ma*************@yahoo.com
wrote:
Ok, valid point.

private volatile bool go = true;
private volatile bool monitorPort = true;

byte[] byteReadStream = null;
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
while (go)
{
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
System.Console.WriteLine("In the loop");
}
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(byteReadStream);
monitorPort = true;
}

It works fine as long as a client keeps connection.
That's still not a complete code sample. And it raises more questions
than it answers. For example:

-- why do you have the "monitorPort" loop at all? assuming that's the
literal code, "byteReadStream" is _never_ going to be null, and so that
loop will always execute the contained block exactly once before exiting

-- why do you decode the bytes you read? you never use the "str"
variable for anything once it's been assigned

-- how do you expect to exit out of the "go" loop? the variable "go"
is initialized to "true" and then never modified

-- in what context does that code appear? what do you expect to
happen when the connection is closed?

Also, as I mentioned before, you _really_ should not be using the
TcpClient.Available property. That said, if you insist, you definitely
should not be passing it as the length parameter for the Stream.Read()
method. It could change between the time you allocate the buffer and the
time you call the Read() method. Just pass "byteReadStream.Length"
instead.

Again, based on the code posted, I'm not surprised your program gets stuck
in an endless, non-yielding loop. That's just what the code you posted
looks like it would do. My guess is that if you fix your code to break
out of the loop when the connection is closed, your problem would go
away. But you would continue to have other the flaws in your code, and
you should really be looking to fix those too.

Pete
Jul 18 '08 #8
<TcpClient.Available property
Yes, I am working on that and on other comments that have been made here.
< how do you expect to exit out of the "go" loop?
This loop is required because of the main purpose of the program I am trying
to adapt.
This is a push server. This product can communicate with .Net code and push
data to the browser from it.
Since my main coding environment is not .Net I am trying to talk to .Net
piece to provide data to be pushed.
One of ideas is to use TCP sockets for that.
So, I am using the push server product's .Net sample and trying to modify it
to aceept external data.
Like I said, it besically works. But now when I am testing the whole thing I
have noticed
that it only works untill I close connection to the c# listener.
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
On Fri, 18 Jul 2008 13:07:41 -0700, Markgoldin <ma*************@yahoo.com>
wrote:
Ok, valid point.

private volatile bool go = true;
private volatile bool monitorPort = true;

byte[] byteReadStream = null;
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
while (go)
{
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
System.Console.WriteLine("In the loop");
}
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(byteReadStream);
monitorPort = true;
}

It works fine as long as a client keeps connection.
That's still not a complete code sample. And it raises more questions
than it answers. For example:

-- why do you have the "monitorPort" loop at all? assuming that's the
literal code, "byteReadStream" is _never_ going to be null, and so that
loop will always execute the contained block exactly once before exiting

-- why do you decode the bytes you read? you never use the "str"
variable for anything once it's been assigned

-- how do you expect to exit out of the "go" loop? the variable "go"
is initialized to "true" and then never modified

-- in what context does that code appear? what do you expect to
happen when the connection is closed?

Also, as I mentioned before, you _really_ should not be using the
TcpClient.Available property. That said, if you insist, you definitely
should not be passing it as the length parameter for the Stream.Read()
method. It could change between the time you allocate the buffer and the
time you call the Read() method. Just pass "byteReadStream.Length"
instead.

Again, based on the code posted, I'm not surprised your program gets stuck
in an endless, non-yielding loop. That's just what the code you posted
looks like it would do. My guess is that if you fix your code to break
out of the loop when the connection is closed, your problem would go
away. But you would continue to have other the flaws in your code, and
you should really be looking to fix those too.

Pete
Jul 18 '08 #9
I didn't test it, but I believe the problem is an infinite loop without wait
state.
This code is an infinite loop of a call to a blocking Stream.Read()
(actually a TCP receive()). As long as the connection is alive, the Read()
shall block execution of yor application most of the time.
When the connection is closed, Read() returnes immediately, so the loop is
executed non-stop and occupies 100% CPU.

Boaz Ben-Porat
Milestone Systems A/S
Denmark
"Markgoldin" <ma*************@yahoo.comskrev i en meddelelse
news:%2****************@TK2MSFTNGP04.phx.gbl...
Ok, valid point.

private volatile bool go = true;
private volatile bool monitorPort = true;

byte[] byteReadStream = null;
TcpClient tcpc = DataAdapterLauncher.tcpl.AcceptTcpClient(); //accept
connection
while (go)
{
while (monitorPort)
{
byteReadStream = new byte[tcpc.Available]; //allocate space for data
tcpc.GetStream().Read(byteReadStream, 0, tcpc.Available);
//read data into byte array
if (byteReadStream != null)
{
monitorPort = false;
}
System.Console.WriteLine("In the loop");
}
string str;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
str = enc.GetString(byteReadStream);
monitorPort = true;
}

It works fine as long as a client keeps connection.
"Peter Duniho" <Np*********@nnowslpianmk.comwrote in message
news:op***************@petes-computer.local...
>On Fri, 18 Jul 2008 11:19:42 -0700, Markgoldin
<ma*************@yahoo.comwrote:
>>[...]
It does work though but with one problem, as soon as a client
disconnects
from my listener, the CPU usage goes up 100% to my exe
and no connections can be made to it.
Any idea?

Not really. You didn't post a concise-but-complete code sample, so
there's no telling what in your code might be stuck in a loop.

That said, it's certainly possible that the loop you posted for some
reason turns out to be the problem. I admit, from the code you posted
it's not clear why your loop works at all (when would "byteReadStream"
ever _not_ be null?). But assuming there's some condition under which
you're not exiting the loop, it wouldn't surprise me to find that you
wind up consuming 100% CPU, because it's probably a scenario in which no
progress towards exiting the loop is made.

You shouldn't be using the Available property anyway. It's not a
reliable indicator of what you can read. But without a complete code
sample, it's not really possible to offer more detailed advice as to how
to fix your program.

Pete


Jul 19 '08 #10

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

Similar topics

1
by: Park Yeon Jo | last post by:
About Error : ORA-12514: TNS:listener could not resolve SERVICE_NAME given in connect descriptor I installed Oracle 8.1.7 on Windows XP Professional. and I wanto connect to that server...
2
by: Cherrish Vaidiyan | last post by:
Hello all, A warm Xmas greetings to all. I have a small problem with starting up the database. Here my strategy. I have installed Oracle 9i R 2 on Red Hat 9. i created two database on this...
1
by: Cherrish Vaidiyan | last post by:
sir, I have a small error in Listener configuration.I have two system with a database in each. I am using Red Hat 9 and Oracle 9i. so i shall anme the database and system. system 1 - node2 ...
5
by: Axel Dachtler | last post by:
Hi, I have a listener problem. The listener cannot read SERVICE_NAME in TNS-Descriptor. The service-name I specified in Oracle Net Manager for this database is testdb as well. ...
1
by: UNIXNewBie | last post by:
I've just installed Oracle Standard on an XP Platform for demo. The listener was not installed. I have installed Oracle many times on 2000 server and never seen an case where the listener was...
3
by: Bill | last post by:
When vb6 Winsock.RemoteHost is set to "127.0.0.1", c# socket listener cannot hear connect request (my old vb6 winsock listener could hear it...). Why doesn't this work, and is there a work...
6
by: Steve Teeples | last post by:
I have been perplexed by how to best treat an event that spans different classes. For example, I have a form which a user inputs data. I want to broadcast that data via an event to another...
0
by: Blake | last post by:
I am trying to make a trace listener textbox that behaves like the output window in VS, in that it shows trace messages from all trace sources. I created my own listener to write to a textbox...
5
by: mivey4 | last post by:
Hi, First off, I am aware that this is a very heavily documented error and I have done my homework for throughly researching probable causes before deciding to post my problem here. At this point,...
1
by: michael ngong | last post by:
michael.john@gmx.at (Michael John) wrote in message news:<90cc4edd.0306230900.28075193@posting.google.com>... MIchael I you stated the OS and platform that could make it easier to address your...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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.