Hi guys:
This topic might sound very familiar to some of you, can some one shed some light or point me to some web link for some sample code or good guide?
I'm able to code for a simple client to server ( one to one) but not this multi client scenario.
The application that i want to establish is simple:
clientx.1--------------> send a request to server for a job
clientx.2--------------> send a request to server for another job
..
....
all this activities have to be concurrent...
how to do this?
Thanks
17 4759 @Jetean
Use ThreadPool wherein you can run your client(s) separately on thread(s).
ie clientx.1-> will run on Thread1
clientx.2-> will run on Thread2...
Hi:
Are you suggesting to have multiple server running on multiple thread?
Is this viable?
Thanks
@Jetean
No no... Its about client. You can have your client on a separate thread which communicates to the server. If you have common resources across the clients, you may have to opt synchronization between your clients.
Can you please clarify what design you are using for "client/server."
Are you using Remoting, WebServices, or hand-coded socket communication?
Are these truly separate clients talking to one server in a separately compiled server application or listener?
If so, what protocol do you use to send and receive job requests?
Mike
OK. I'm using Socket. The application is to serve multiple PCs within the same office. 1 server and multiple clients. I think i can handle the client side but I'm not sure about the Server side program. How to do it?
One more condition is that The Server has to continously scan for any new connection and new incoming request..
For the listener, I would suggest you start by studying the System.Net.Sockets.TcpListener class, as this will take care much of the infrastructure of listening for socket connection requests and reading them.
mldisibio:
I'm looking at Asynchronous TCP Server. I'm not quite sure how to implement it. With many Clients sending data back to Server, Will one Client Keep Connected to the server preventing access from other Clients?
Is it something like your TCP SERVER(which you will be developing) has to perform normal tasks(irrespective of the operations) along with SERVING YOUR CLIENTS(each client is a separate PC)! Are you seeking Asynchronus SERVER for this purpose?
The 'de facto' way to do this is to run a simple loop that accepts new clients. Once accepted the new socket/client is passed to a new thread that serves the client through that socket. Once done, the thread simply dies. Shared resources should be synchronized among the several client serving threads.
kind regards,
Jos
Jos is actually right (pause for recovery of blockbuster news).
Generally, you will have thread that sets up the listener socket, loops around accepting connections (syncronous or asyncronous), and starts a new thread for each new connection. Thread loop should take steps to not be a busy loop.
Each of your spawned threads will handle interaction with the connected client.
This is similar to the way a webserver works.
- using System;
-
using System.Collections.Generic;
-
using System.ComponentModel;
-
using System.Data;
-
using System.Drawing;
-
using System.Linq;
-
using System.Text;
-
using System.Windows.Forms;
-
-
using System.Net;
-
using System.Net.Sockets;
-
using System.Diagnostics;
-
-
using System.IO;
-
-
namespace Server
-
{
-
public partial class ServerForm : Form
-
{
-
Dictionary<string, string> dictionary;
-
-
const int BUFFER_SIZE = 1024;
-
byte[] rcvBuffer = new byte[BUFFER_SIZE]; // To recieve data from the client
-
-
Socket serverSocket;
-
int socketCounter = 0;
-
Dictionary<Socket, int> clientSocketDictionary = new Dictionary<Socket, int>();
-
-
const int PORT = 3333;
-
-
public ServerForm()
-
{
-
InitializeComponent();
-
FillDictionary();
-
StartServer();
-
}
-
-
//Construct server socket and bind it to all local netowrk interfaces, then listen for connections
-
void StartServer()
-
{
-
try
-
{
-
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
-
serverSocket.Listen(10); // Listen(10) means we can handle
-
// 10 clients requests simultaneously
-
serverSocket.BeginAccept(AcceptCallback, null);
-
}
-
catch (Exception ex) { AppendToTextBox(ex.Message); }
-
}
you must determine the client ip first !
- void AcceptCallback(IAsyncResult AR)
-
{
-
try
-
{
-
Socket tempSocket = serverSocket.EndAccept(AR); // Client connected successfully, waiting for requests
-
-
tempSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None, ReceiveCallback, tempSocket);
-
-
socketCounter++;
-
clientSocketDictionary.Add(tempSocket, socketCounter);
-
-
AppendToTextBox("Client " + socketCounter + " connected successfully...");
-
-
byte[] replyBuffer = Encoding.ASCII.GetBytes("Connected successfully...");
-
tempSocket.Send(replyBuffer);
-
-
serverSocket.BeginAccept(AcceptCallback, null);
-
}
-
-
catch (Exception ex) { AppendToTextBox(ex.Message); }
-
}
-
-
void ReceiveCallback(IAsyncResult AR)
-
{
-
Socket tempSocket = (Socket)AR.AsyncState;
-
int bytesReceived = 0;
-
int clientNumber = clientSocketDictionary[tempSocket];
-
-
try
-
{
-
bytesReceived = tempSocket.EndReceive(AR); // Get number of bytes received
-
}
-
catch (Exception ex)
-
{
-
AppendToTextBox("Exception: " + ex.Message + "...");
-
tempSocket.Close();
-
clientSocketDictionary.Remove(tempSocket);
-
}
-
-
if (bytesReceived > 0)
-
{
-
byte[] rcvBufferTrim = new byte[bytesReceived];
-
Array.Copy(rcvBuffer, rcvBufferTrim, bytesReceived); // Removes trailing nulls
-
string rcvText = Encoding.ASCII.GetString(rcvBufferTrim); // Convert bytes into string
-
rcvText = rcvText.ToLower().ToString();
-
-
string replyText = "";
-
DateTime time = DateTime.Now;
-
-
#region Switch statement for received text, check for special requests
-
switch (rcvText)
-
{
-
case "gettime":
-
AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
-
replyText = "Time is : " + time.ToString("HH:MM:ss");
-
break;
-
case "getdate":
-
AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
-
replyText = "Date is : " + time.ToString("dd/mm/yyyy");
-
break;
-
case "disconnect":
-
tempSocket.Shutdown(SocketShutdown.Both);
-
tempSocket.Close();
-
clientSocketDictionary.Remove(tempSocket);
-
AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection");
-
return;
-
default:
-
AppendToTextBox("Received from client [" + clientNumber.ToString() + "]: " + rcvText);
-
if (dictionary.ContainsKey(rcvText))
-
replyText = dictionary[rcvText];
-
else
-
replyText = "Not Found";
-
break;
-
}
-
#endregion
-
-
// Send the reply text
-
byte[] replyBuffer = Encoding.ASCII.GetBytes(replyText);
-
tempSocket.Send(replyBuffer);
-
-
// Starts receiving data again
-
tempSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length,
-
SocketFlags.None, new AsyncCallback(ReceiveCallback), tempSocket);
-
}
-
else
-
{
-
try
-
{
-
tempSocket.Shutdown(SocketShutdown.Both);
-
tempSocket.Close();
-
clientSocketDictionary.Remove(tempSocket);
-
AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection");
-
}
-
catch { AppendToTextBox("Client [" + clientNumber.ToString() + "] closed connection"); }
-
}
-
}
-
-
// Provides a thread-safe way to append text to the textbox
-
void AppendToTextBox(string text)
-
{
-
MethodInvoker invoker = new MethodInvoker(delegate
-
{
-
textBox.Text += text + "\r\n";
-
textBox.SelectionStart = textBox.TextLength;
-
textBox.ScrollToCaret();
-
}); // "\r\n" are for new lines
-
this.Invoke(invoker);
-
}
-
-
// Add all entries to fill the dictionary
-
void FillDictionary()
-
{
-
string[] lines = File.ReadAllLines("IPaddresses.txt");
-
dictionary = lines.Select(l => l.Split(':')).ToDictionary(a => a[0], a => a[1]);
-
}
-
-
private void textBox_TextChanged(object sender, EventArgs e)
-
{
-
-
}
-
}
-
}
this is the client code ! You can try it .
- namespace Client
-
{
-
public partial class ClientForm : Form
-
{
-
const int BUFFER_SIZE = 1024;
-
byte[] sendBuffer = new byte[BUFFER_SIZE];
-
-
byte[] rcvBuffer = new byte[BUFFER_SIZE];
-
Socket clientSocket;
-
const int PORT = 3333;
-
-
public ClientForm()
-
{
-
InitializeComponent();
-
}
-
-
void btnConnect_Click(object sender, EventArgs e)
-
{
-
string serverIP = "192.168.1.200";
-
try
-
{
-
this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
// Connect to the local host
-
clientSocket.Connect(new IPEndPoint(IPAddress.Parse(serverIP), PORT));
-
// Prepares to receive something, i.e. the echo
-
clientSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None, ReceiveCallback, null);
-
EnableSendButton();
-
}
-
catch (Exception ex) { AppendToTextBox(ex.Message); }
-
}
-
-
void btnSend_Click(object sender, EventArgs e)
-
{
-
try
-
{
-
// Serialize the textBox text before sending
-
sendBuffer = Encoding.ASCII.GetBytes(textBoxInput.Text);
-
-
// Sends contents of textbox to the server
-
clientSocket.Send(sendBuffer);
-
-
// Prepares to receive something, i.e. the echo
-
clientSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None, ReceiveCallback, null);//.Receive(rcvBuffer);
-
}
-
catch (Exception ex) { AppendToTextBox(ex.Message); }
-
}
-
-
// About Asynchronous Callbacks: http://stackoverflow.com/questions/1...-asynccallback
-
void ReceiveCallback(IAsyncResult AR)
-
{
-
try
-
{
-
int bytesReceived = clientSocket.EndReceive(AR); // Number of bytes received
-
if (bytesReceived == 0) return;
-
byte[] rcvBufferTrim = new byte[bytesReceived];
-
Array.Copy(rcvBuffer, rcvBufferTrim, bytesReceived); // Removes trailing nulls
-
string text = Encoding.ASCII.GetString(rcvBufferTrim); // Convert bytes into string
-
AppendToTextBox(DateTime.Now.ToString("HH:mm:ss") + ": " + text); // Displays buffer contents as text
-
-
// Starts receiving data again
-
clientSocket.BeginReceive(rcvBuffer, 0, rcvBuffer.Length, SocketFlags.None, ReceiveCallback, null);
-
}
-
catch (Exception ex) { AppendToTextBox(ex.Message); }
-
}
-
-
// Provides a thread-safe way to enable the send button/disable the connect button
-
void EnableSendButton()
-
{
-
MethodInvoker invoker = new MethodInvoker(delegate
-
{
-
btnSend.Enabled = true;
-
btnConnect.Enabled = false;
-
btnDisconnect.Enabled = true;
-
textBoxInput.ReadOnly = false;
-
btnDisconnect.Enabled = true;
-
});
-
this.Invoke(invoker);
-
}
-
-
private void textBoxInput_KeyDown(object sender, KeyEventArgs e)
-
{
-
if (btnSend.Enabled == true
-
&& Control.ModifierKeys != Keys.Shift
-
&& e.KeyCode == Keys.Return)
-
{
-
MethodInvoker invoker = new MethodInvoker(delegate { btnSend.PerformClick(); });
-
this.Invoke(invoker);
-
e.SuppressKeyPress = true;
-
}
-
}
-
-
// Provides a thread-safe way to append text to the textbox
-
void AppendToTextBox(string text)
-
{
-
MethodInvoker invoker = new MethodInvoker(delegate
-
{
-
textBoxDisplay.Text += text + "\r\n";
-
textBoxDisplay.SelectionStart = textBoxDisplay.TextLength;
-
textBoxDisplay.ScrollToCaret();
-
}); // "\r\n" are for new lines
-
try { this.Invoke(invoker); }
-
catch { };
-
}
-
-
private void btnDisconnect_Click(object sender, EventArgs e)
-
{
-
sendBuffer = Encoding.ASCII.GetBytes("disconnect");
-
clientSocket.Send(sendBuffer);
-
-
clientSocket.Shutdown(SocketShutdown.Both);
-
clientSocket.Close();
-
-
this.Close(); // Close the window
-
}
-
-
private void textBoxDisplay_TextChanged(object sender, EventArgs e)
-
{
-
-
}
-
}
-
}
Don't forget this for client : - using System;
-
using System.Collections.Generic;
-
using System.ComponentModel;
-
using System.Data;
-
using System.Drawing;
-
using System.Linq;
-
using System.Text;
-
using System.Windows.Forms;
-
-
using System.Net;
-
using System.Net.Sockets;
Sign in to post your reply or Sign up for a free account.
Similar topics
by: canigou9 (remove your socks to reply) |
last post by:
(cross posted - comp.databases.ms-access, microsoft.public.access)
Hello folks - this is my first post here, after a short lurk.
I have written an application in Access2002 for a friend's...
|
by: Parahat Melayev |
last post by:
I am trying to writa a multi-client & multi-threaded TCP server.
There is a thread pool. Each thread in the pool will handle requests
of multiple clients.
But here I have a problem. I find a...
|
by: Sharon Tal |
last post by:
Hi to all.
I'm developing a web multi player game.
The game will run on the server, and the clients will just show it.
All the clients will have few events, by which they can change the game...
|
by: Roger |
last post by:
Hi:
I'm trying to perform a multi-select in a datagrid using a ButtonColumn.
Anyone know how to do this?
Roger
|
by: bobwansink |
last post by:
Hi, I'm relatively new to programming and I would like to create a C++
multi user program. It's for a project for school. This means I will
have to write a paper about the theory too. Does anyone...
|
by: Nick Caramello |
last post by:
We are in the process of prototyping an architecture for a multi-tier
application, and have run into the following problem:
1) We have a client application who calls a method sending over a...
|
by: Jeff |
last post by:
Hello everyone. I've searched through the archives here, and it seems
that questions similar to this one have come up in the past, but I was
hoping that I could pick your Pythonic brains a bit.
...
|
by: dantz |
last post by:
Hi,
I am wondering how should I implement my multi client-server application.
When the connection of a client is established with the server and the exchange was done, can I just retain the...
|
by: Curtis Rutland |
last post by:
Building A Silverlight (2.0) Multi-File Uploader
All source code is C#. VB.NET source is coming soon.
Note: This project requires Visual Studio 2008 SP1 or Visual Web Developer 2008 SP1 and...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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...
|
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...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |