Client server socket program for sending receiving messages


In this code snippet we will see how to work with client and server using tcp server using sockets to send message from client to server. This type of article may have been posted on many sites but i created it in Console and Windows and working fine on my controls. Now i will tell you what to do and how it works.

Step 1 : Create two windows forms named Server and Client

Design UI of server and it looks like this :
UI of server

Step 2 : Write below code on Server.cs


using System.Net;
using System.Net.Sockets;

// Declare two public variables to use it anywhere
public string ipaddress;
public int portno;


Step 3 : Write below code on Server.cs

private void Server_Load(object sender, EventArgs e)
{
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());

foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipaddress = ip.ToString();
lblIPAdd.Text = ipaddress;
}
}
}

private void txtPortNo_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
btnSubmit.Focus();
}
}

private void txtPortNo_Leave(object sender, EventArgs e)
{
if (txtPortNo.Text != null && (Convert.ToInt32(txtPortNo.Text) < 1 || Convert.ToInt32(txtPortNo.Text) > 65535))
{
MessageBox.Show("Please enter valid port no between 1-65535.", "Invalid Port Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPortNo.Focus();
}
}


Step 4 : Write below code on button click event in Server.cs

try
{
portno = Convert.ToInt32(txtPortNo.Text);
IPAddress ipAd = IPAddress.Parse(lblIPAdd.Text);

// use local m/c IP address, and
// use the same in the client

/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, portno);

/* Start Listeneting at the specified port */
myList.Start();

richTextBox1.Text = "This server is runnig at port : " + txtPortNo.Text + Environment.NewLine;
richTextBox1.Text += "The local End point is : " + myList.LocalEndpoint + Environment.NewLine;
richTextBox1.Text += "Waiting to accept a connection from client...." + Environment.NewLine;

Client c = new Client(ipaddress, portno);
c.ShowDialog();

Socket s = myList.AcceptSocket();

richTextBox1.Text += "Connection accepted from : " + s.RemoteEndPoint + Environment.NewLine;
richTextBox1.Text += "The string was received by the server is :" + Environment.NewLine + Environment.NewLine;
richTextBox1.Text += c.richTextBox1.Text + Environment.NewLine;

s.Close();
myList.Stop();
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


Your connection output will look like this :
Client connection

Step 5 : Write below code on Client.cs

Design UI of client and it looks like this :
Client message for server


using System.Net;
using System.Net.Sockets;

string msg, ip;
int port;
TcpClient tcpclnt = new TcpClient();
Server sr = new Server();

// Default constructor of Client class
public Client(string ipaddress, int portno)
{
InitializeComponent();
ip = ipaddress;
port = portno;
}

private void Client_Load(object sender, EventArgs e)
{
try
{
tcpclnt.Connect(ip, port);
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}


Step 6 : Write below code on button client event in Client.cs

try
{
if (richTextBox1.Text != null || richTextBox1.TextLength > 0)
{
msg = "Sending your message to server...";
flag = true;
message();

tcpclnt.Close();
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}


Your final output means message of client will be transferred to server.
Response from client to server


Article by Nirav Lalan
Regards, Nirav Lalan DNS Gold Member "If you can dream it, you can do it."

Follow Nirav Lalan or read 17 articles authored by Nirav Lalan

More articles: TCP/IP Sockets in C#

Comments

Author: Jayakumar.R28 Jul 2015 Member Level: Gold   Points : 2

Hi
Nirav

look this
Step 4 : Write below code on button click event in Server.cs

richTextBox1.Text

But this code you mention server.cs

But Client Side form only Richtext1 in your design

I tried not working . Can you post full project for this?

Author: Nirav Lalan28 Jul 2015 Member Level: Gold   Points : 2

Hello Kumar,

See my article properly.
There is richTextBox1 in client and server both.

See this line of code in Step 4:
richTextBox1.Text += c.richTextBox1.Text + Environment.NewLine; // c is an object of client class. so i am accessing value of richTextBox1 of client class on the server form.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: