Client Server in C#

  • (3 Pages)
  • +
  • 1
  • 2
  • 3

41 Replies - 5945 Views - Last Post: 06 March 2009 - 07:28 AM Rate Topic: -----

#1 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Client Server in C#

Post icon  Posted 02 March 2009 - 09:50 PM

//This is the server code im using
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServer
{
	public static void Main()
	{try
		{
			int recv;
			byte[] data = new byte[1024];
			IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			newsock.Bind(ipep);
			Console.WriteLine("Waiting for a client...");			
			IPEndPoint sender = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
			EndPoint tmpRemote = (EndPoint)(sender);
			recv = newsock.ReceiveFrom(data, ref tmpRemote);
			Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
			Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
			data = new byte[1024];
			string ss = "Welcome to the Server";
			data = Encoding.ASCII.GetBytes(ss);
			newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
			Console.WriteLine("\nSent Acknowledgement");
		   // newsock.Close();		   
		}
		catch (Exception e)
		{
			Console.WriteLine("Error..... " + e.StackTrace);
		}
	   // Console.ReadLine();	  
	}
}

//This is the client code which im calling inside a button click event
 private void Send_Click(object sender, EventArgs e)
		{
			Callback();}		
		private void Callback()
		{try
			{			  
				byte[] data = new byte[1024];
				listBox3.Items.Add("Connecting....");
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
	   Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);								
				listBox3.Items.Add("Connected");								
				data = Encoding.ASCII.GetBytes("hello");
				listBox3.Items.Add("Transmitting...");
				server.SendTo(data, data.Length, SocketFlags.None, ipep);//sent hello
				listBox3.Items.Add("Sent...");
	  IPEndPoint sender = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				EndPoint tmpRemote = (EndPoint)sender;
				listBox3.Items.Add("Message received from {0}:");
				listBox3.Items.Add(tmpRemote.ToString());
				data = new byte[1024];
				int recv = server.ReceiveFrom(data, ref tmpRemote);
				listBox3.Items.Add(Encoding.ASCII.GetString(data,0,recv));
				//listBox3.Items.Add("Stopping client");
				//server.Close();}			
			catch (Exception e)
			{
				Console.WriteLine("Error..... " + e.StackTrace);
			}
			Console.ReadLine();}


When i run this code:
My form design is as follows:
With a button click i list the drives in the system,then with another button click i list the folders in each drive,and then listing the exe files in the folder..I have set a default path say C:\projects\ports.The ports folders in turn contains many folders like 10000,10001 etc..I have copied the exe file obtained when compiling the Server Application to 10000...So with a button click event i will get the exe of the server application which should act as server and i have defined the client in the Form1.cs..Now when i have another button click the message(which i have defined inside the code)should be sent to the exe(i.e.server) opened...Please check my code and tell me whether i should make any changes.
Right now when i run this application the exe(server)window closes when i click "Send" button to send the message to the exe...Please help me with this

Is This A Good Question/Topic? 0
  • +

Replies To: Client Server in C#

#2 n8wxs   User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Client Server in C#

Posted 02 March 2009 - 11:35 PM

The server console window closes because you have commented out this line // Console.ReadLine();

I built 2 projects - The UDPServer console window, and added your Send_Click code to another project of mine. Both functioned as you wrote them. See attached image.

Attached image(s)

  • Attached Image

Was This Post Helpful? 0
  • +
  • -

#3 djkitt   User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 192
  • Joined: 22-May 08

Re: Client Server in C#

Posted 02 March 2009 - 11:52 PM

View PostPoornima Mani, on 2 Mar, 2009 - 10:50 PM, said:

Right now when i run this application the exe(server)window closes when i click "Send" button to send the message to the exe...Please help me with this


So, if you want the server to stay open put a while loop around the callback code:

bool done=false;
while(!done)
{
			recv = newsock.ReceiveFrom(data, ref tmpRemote);
			Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
			Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
			data = new byte[1024];
			string ss = "Welcome to the Server";
			data = Encoding.ASCII.GetBytes(ss);
			newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
			Console.WriteLine("\nSent Acknowledgement");
}





Hope this helps,

Kitt

This post has been edited by djkitt: 02 March 2009 - 11:53 PM

Was This Post Helpful? 0
  • +
  • -

#4 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 12:19 AM

View Postn8wxs, on 2 Mar, 2009 - 10:35 PM, said:

The server console window closes because you have commented out this line // Console.ReadLine();

I built 2 projects - The UDPServer console window, and added your Send_Click code to another project of mine. Both functioned as you wrote them. See attached image.

Hi,
I have removed the comment line for Console.ReadLine(); but still it closes..Should i include this Console.ReadLine() else where...
I could not sort out the mistake...Please give me your suggestions

View Postdjkitt, on 2 Mar, 2009 - 10:52 PM, said:

View PostPoornima Mani, on 2 Mar, 2009 - 10:50 PM, said:

Right now when i run this application the exe(server)window closes when i click "Send" button to send the message to the exe...Please help me with this


So, if you want the server to stay open put a while loop around the callback code:

bool done=false;
while(!done)
{
			recv = newsock.ReceiveFrom(data, ref tmpRemote);
			Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
			Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
			data = new byte[1024];
			string ss = "Welcome to the Server";
			data = Encoding.ASCII.GetBytes(ss);
			newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
			Console.WriteLine("\nSent Acknowledgement");
}





Hope this helps,

Kitt

Hi
I am not able to get you.In the post above you have included a while loop in the server code,but you had asked to include a while loop around the callback code..Please explain me this
Was This Post Helpful? 0
  • +
  • -

#5 djkitt   User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 192
  • Joined: 22-May 08

Re: Client Server in C#

Posted 03 March 2009 - 12:20 AM

Quote

Hi
I am not able to get you.In the post above you have included a while loop in the server code,but you had asked to include a while loop around the callback code..Please explain me this


I meant where the callback is handled. In your server code. Where I put the while loop.

Sorry if I wasn't clear.

Anyway,

Your server code is waiting for the client to send something... The client sends something... the server handles it ... and then the server closes.

If you want the server to stay open you need to put a loop around the code that handles what is sent from the client... like in my example.

This post has been edited by djkitt: 03 March 2009 - 12:23 AM

Was This Post Helpful? 0
  • +
  • -

#6 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 12:22 AM

View Postn8wxs, on 2 Mar, 2009 - 10:35 PM, said:

The server console window closes because you have commented out this line // Console.ReadLine();

I built 2 projects - The UDPServer console window, and added your Send_Click code to another project of mine. Both functioned as you wrote them. See attached image.

Hi
I saw the attached image..Actually im getting the output on the client i.e. the list box..But for some reason when i click the send button exe closes and displays the output on the listbox
Was This Post Helpful? 0
  • +
  • -

#7 djkitt   User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 192
  • Joined: 22-May 08

Re: Client Server in C#

Posted 03 March 2009 - 12:40 AM

View PostPoornima Mani, on 3 Mar, 2009 - 01:22 AM, said:

Hi
I saw the attached image..Actually im getting the output on the client i.e. the list box..But for some reason when i click the send button exe closes and displays the output on the listbox


So,
Your server app 'exe' hooks up to a port and waits for something to come in on it (sorry, I called this callback code in my first reply).

Your client app sends something out on that port and waits for something as well (a callback).

'exe' receives the client's output and sends something back to the waiting client. Then it closes because it is a console app and once it is done - it is done. (To keep your console app alive you need a loop.)

The client receives the data from 'exe' and happily displays it in the listbox and stays alive because it is in a windows form.

Sorry if my use of the term callback in my original replay caused some confusion. I was refering to the place in the server code that was waiting for a client...not a callback.


Hope this helps,


Kitt
Was This Post Helpful? 0
  • +
  • -

#8 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 12:40 AM

View Postdjkitt, on 2 Mar, 2009 - 11:20 PM, said:

Quote

Hi
I am not able to get you.In the post above you have included a while loop in the server code,but you had asked to include a while loop around the callback code..Please explain me this


I meant where the callback is handled. In your server code. Where I put the while loop.

Sorry if I wasn't clear.

Anyway,

Your server code is waiting for the client to send something... The client sends something... the server handles it ... and then the server closes.

If you want the server to stay open you need to put a loop around the code that handles what is sent from the client... like in my example.

Hi
Thanks for the explanation..I am clear now..
I had a try with what you suggested but still the server closes..
Please can you give me any other suggestions...Actually im getting the output on the client(i.e.in the listbox control) but im not able to see the sent message on the server
Was This Post Helpful? 0
  • +
  • -

#9 djkitt   User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 192
  • Joined: 22-May 08

Re: Client Server in C#

Posted 03 March 2009 - 12:50 AM

View PostPoornima Mani, on 3 Mar, 2009 - 01:40 AM, said:

Hi
Thanks for the explanation..I am clear now..
I had a try with what you suggested but still the server closes..
Please can you give me any other suggestions...Actually im getting the output on the client(i.e.in the listbox control) but im not able to see the sent message on the server


Would you mind posting the code you tried in the console app (exe)? That should have worked. I just tested it here on my end and it worked fine. The server stays open and displays

Message received from 127.0.0.1:###:
hello

Thanks,

Kitt


Here is a copy of the code I entered for the sever app (exe)...

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServer
{
	public static void Main()
	{
		string a = "";

			try
			{
				int recv;
				byte[] data = new byte[1024];
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				newsock.Bind(ipep);
				Console.WriteLine("Waiting for a client...");			
				IPEndPoint sender = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				EndPoint tmpRemote = (EndPoint)(sender);
				bool done=false;
				while(!done)
				{
				recv = newsock.ReceiveFrom(data, ref tmpRemote);
				Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
				Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
				data = new byte[1024];
				string ss = "Welcome to the Server";
				data = Encoding.ASCII.GetBytes(ss);
				newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
				Console.WriteLine("\nSent Acknowledgement");
				}

				// newsock.Close();		   
			}
			catch (Exception e)
			{
				Console.WriteLine("Error..... " + e.StackTrace);
			}
	}
}


Was This Post Helpful? 0
  • +
  • -

#10 n8wxs   User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: Client Server in C#

Posted 03 March 2009 - 01:13 AM

View PostPoornima Mani, on 2 Mar, 2009 - 11:19 PM, said:

I have removed the comment line for Console.ReadLine(); but still it closes..Should i include this Console.ReadLine() else where...

I meant that you should uncomment out that line, not remove or move it.
And yes you need to add another Console.ReadLine(); statement. This one goes in the catch block after the the Console.WriteLine();. Without it, if the code throws an exception you won't see it because the console window will close.

Also, in your Send_Click method's Callback() function, the Console.WriteLine() and Console.ReadLine() functions will not work. You are in a Forms environment, not a console app one. You need to either use something like a MessageBox or have a status display, textbox, label, listbox, etc., on your form to display the catch blocks error stack trace.

This post has been edited by n8wxs: 03 March 2009 - 01:13 AM

Was This Post Helpful? 0
  • +
  • -

#11 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 01:37 AM

View Postdjkitt, on 2 Mar, 2009 - 11:50 PM, said:

View PostPoornima Mani, on 3 Mar, 2009 - 01:40 AM, said:

Hi
Thanks for the explanation..I am clear now..
I had a try with what you suggested but still the server closes..
Please can you give me any other suggestions...Actually im getting the output on the client(i.e.in the listbox control) but im not able to see the sent message on the server


Would you mind posting the code you tried in the console app (exe)? That should have worked. I just tested it here on my end and it worked fine. The server stays open and displays

Message received from 127.0.0.1:###:
hello

Thanks,

Kitt


Here is a copy of the code I entered for the sever app (exe)...

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UdpServer
{
	public static void Main()
	{
		string a = "";

			try
			{
				int recv;
				byte[] data = new byte[1024];
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
				newsock.Bind(ipep);
				Console.WriteLine("Waiting for a client...");			
				IPEndPoint sender = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				EndPoint tmpRemote = (EndPoint)(sender);
				bool done=false;
				while(!done)
				{
				recv = newsock.ReceiveFrom(data, ref tmpRemote);
				Console.WriteLine("Message received from {0}:", tmpRemote.ToString());
				Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
				data = new byte[1024];
				string ss = "Welcome to the Server";
				data = Encoding.ASCII.GetBytes(ss);
				newsock.SendTo(data, data.Length, SocketFlags.None, tmpRemote);
				Console.WriteLine("\nSent Acknowledgement");
				}

				// newsock.Close();		   
			}
			catch (Exception e)
			{
				Console.WriteLine("Error..... " + e.StackTrace);
			}
	}
}



Actually when i tried this for the 1st time i compiled and run the server application in the command prompt and the client using the start debugging option...The server was alive...

Then i changed according to my requirement but now the server closes...I had a try with the while loop you suggested but stil im not getting it...
Was This Post Helpful? 0
  • +
  • -

#12 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 01:46 AM

View Postn8wxs, on 2 Mar, 2009 - 10:35 PM, said:

The server console window closes because you have commented out this line // Console.ReadLine();

I built 2 projects - The UDPServer console window, and added your Send_Click code to another project of mine. Both functioned as you wrote them. See attached image.

Hi
In the image you have attached i could see the server staying alive..
I have included the Console.ReadLine(); even in the catch block but stil im not getting it...What is that i should do to keep the server alive like the one you have done
Was This Post Helpful? 0
  • +
  • -

#13 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 05:46 AM

View Postdjkitt, on 2 Mar, 2009 - 11:40 PM, said:

View PostPoornima Mani, on 3 Mar, 2009 - 01:22 AM, said:

Hi
I saw the attached image..Actually im getting the output on the client i.e. the list box..But for some reason when i click the send button exe closes and displays the output on the listbox


So,
Your server app 'exe' hooks up to a port and waits for something to come in on it (sorry, I called this callback code in my first reply).

Your client app sends something out on that port and waits for something as well (a callback).

'exe' receives the client's output and sends something back to the waiting client. Then it closes because it is a console app and once it is done - it is done. (To keep your console app alive you need a loop.)

The client receives the data from 'exe' and happily displays it in the listbox and stays alive because it is in a windows form.

Sorry if my use of the term callback in my original replay caused some confusion. I was refering to the place in the server code that was waiting for a client...not a callback.


Hope this helps,


Kitt

Hi
I have another doubt regarding this application..Even before i open the server,if i click the send the message is displayed on the listbox..It is server which has to send a message as an acknowledgement to the client once it gets the message from the client...In such case is my code right?If not what changes are required?Please help me with this.Thanks for any help in advance.
Was This Post Helpful? 0
  • +
  • -

#14 Poornima Mani   User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 178
  • Joined: 25-January 09

Re: Client Server in C#

Posted 03 March 2009 - 06:28 AM

View Postn8wxs, on 2 Mar, 2009 - 10:35 PM, said:

The server console window closes because you have commented out this line // Console.ReadLine();

I built 2 projects - The UDPServer console window, and added your Send_Click code to another project of mine. Both functioned as you wrote them. See attached image.

Hi
Please can you tell me the change that has to be done to keep the server stay alive....Im trying for a long time, I couldnt get it
Was This Post Helpful? 0
  • +
  • -

#15 djkitt   User is offline

  • D.I.C Head

Reputation: 29
  • View blog
  • Posts: 192
  • Joined: 22-May 08

Re: Client Server in C#

Posted 03 March 2009 - 10:53 AM

View PostPoornima Mani, on 3 Mar, 2009 - 06:46 AM, said:

Hi
I have another doubt regarding this application..Even before i open the server,if i click the send the message is displayed on the listbox..


Hi,

I see what you are getting at. You just need to move some lines of code in your client app.

private void Send_Click(object sender, EventArgs e)
		{
			Callback();}		
		private void Callback()
		{try
			{			  
				byte[] data = new byte[1024];
				listBox3.Items.Add("Connecting....");
				IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
	   Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);								
				listBox3.Items.Add("Connected");								
				data = Encoding.ASCII.GetBytes("hello");
				listBox3.Items.Add("Transmitting...");

// ----The Line Below this comment is where you are sending data to the port (Whether server it is running or not)
				server.SendTo(data, data.Length, SocketFlags.None, ipep);//sent hello
				listBox3.Items.Add("Sent...");
	  IPEndPoint sender = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
				EndPoint tmpRemote = (EndPoint)sender;

// ----The Line Below this comment is where you are writing info to the listBox before you have received any info back from the Server.

				listBox3.Items.Add("Message received from {0}:");
				listBox3.Items.Add(tmpRemote.ToString());
				data = new byte[1024];

// ----The Line Below this comment is where you are waiting for the Server to Reply 
				int recv = server.ReceiveFrom(data, ref tmpRemote);
				listBox3.Items.Add(Encoding.ASCII.GetString(data,0,recv));

				//listBox3.Items.Add("Stopping client");
				//server.Close();}			
			catch (Exception e)
			{
				Console.WriteLine("Error..... " + e.StackTrace);
			}
			Console.ReadLine();}





You should probably move the code that says that a Message has been received from the server below the code waiting for the server to reply.

---

OK - I don't know whether you understand the difference between what is happening in your client app and what is happening in your server app.


CLIENT APP:

When you click your button CallBack() is executed. It creates a socket connection. It sends data out over that socket and then asks for info back over that socket. Then the socket is destoyed. There is no more communication with the server until the button is pressed again.


SERVER APP:

When you execute the server app it creates a socket and waits for data to come in on that socket. When data does come in it sends something back and then the program closes. Unlike your client program, which is a Windows Forms program, the server app will not continue to run once it has handled the data received from the client app.

If you want the server to continue to wait for info from the client you must execute the line below again:
				recv = newsock.ReceiveFrom(data, ref tmpRemote);



Just putting a "Console.ReadLine" after the server has recieved data will not make the server continue to receive data. It will just allow you to see what the server app has output.

If you hit enter the server app will close. If you don't hit enter the server app will do nothing. It will just sit there waiting for the user to press enter.

This can be confusing, but let me make it as clear as I can:

When the code called by sendClick() ends your Windows Form will still run. You can still push buttons.

When the code in your console app has finished executing the application will end. (This is why you need a loop. To keep the code from ending and to request data from the client again.)

----

I am still not sure if I have been clear. Let me know if this doesn't make sense.

-Kitt

This post has been edited by djkitt: 03 March 2009 - 10:56 AM

Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3