471,348 Members | 1,455 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

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

Multiple socket clients

Here is code I am using to create a socket listener:
public void Run()

{

go = true;

Random rand = new Random();

// Buffer for reading data

Byte[] bytes = new Byte[1024];

String data = null;

while (go)

{

TcpClient tcpc = FromAnotherClass.tcpl.AcceptTcpClient(); //accept
connection

data = null;

// Get a stream object for reading and writing

NetworkStream stream = tcpc.GetStream();

// Loop to receive all the data sent by the client.

int i;

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.

if (data != "")

{

System.Console.WriteLine(data);

}

}

Thread.Sleep(1000 + rand.Next(2000));

}

}

My question is can this code handle connections from multiple clients?

Or should I have a separate listener for each client?

Thanks for help.
Jul 30 '08 #1
3 1391
>
My question is can this code handle connections from multiple clients?

Or *should I have a separate listener for each client?
You need to have one thread listening for connection, and when a
connection is received a new thread is spawned to handle it.

I have posted similar code in the past, it's very easily done with a
Sync Queue.

Look in the archive or post back if you do not find my old posts
Jul 30 '08 #2
found the post:

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 30 '08 #3
This is a bit above my head. How do I pull data from it?
"Ignacio Machin ( .NET/ C# MVP )" <ig************@gmail.comwrote in
message
news:64**********************************@l42g2000 hsc.googlegroups.com...
found the post:

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 30 '08 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Sharon | last post: by
2 posts views Thread by jasonsgeiger | last post: by
1 post views Thread by Riddle | last post: by

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.