General discussion

Locked

Socket Programming in c#

By vijayykaushik ·
Hello friends
This is my first post ..I am developing an intranet application in c#.net which will be used to communicate betwwen any two system on the network.
I have used the methodology where every system will ast as server as well as client.
But i am facing problem in sending message from one system to another. I am pasting my code aswell ..please see and suggest something fruitful.
In Networkhandler class library of project I made a new class AsynchronousSocketListener which will listen to specified port.
Why Asynchronous?
Asynchronous operations are typically used to perform tasks that might take a long time to complete, such as opening large files, connecting to remote computers, or querying a database. An asynchronous operation executes in a thread separate from the main application thread. When an application calls methods to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.
In AsynchronousSocketListener Class I designed a method StartListening() This method start the server at a given port.
Constructor of Class
public AsynchronousSocketListener(int Port)
{
ListenToPort = Port;
}
StartListening Method
/// <summary>
/// starts server at given port...
/// "AcceptCallback" is called when connection request comes
/// </summary>
public void StartListening()
{
byte[] bytes = new Byte[1024];

IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, ListenToPort);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
//Console.WriteLine(e.Message);
MessageBox.Show(e.ToString());
}
}
AcceptCallback Method
public void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
//EndAccept-Asynchronously accepts an incoming connection attempt and creates a new Socket to handle remote host communication.
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
try
{
//BeginReceive-Begins to asynchronously receive data from a connected Socket.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
catch (Exception)
{
//Console.WriteLine();
MessageBox.Show(e.ToString());

}
}
ReadCallback Method
public void ReadCallback(IAsyncResult ar)
{
try
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.Unicode.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// Send(handler, content);
String remoteHost = handler.RemoteEndPoint.ToString();
String ip = remoteHost.Remove(remoteHost.IndexOf(':'));
String sender = Dns.GetHostEntry(IPAddress.Parse(ip)).HostName;

//String sender = Dns.GetHostByAddress(IPAddress.Parse("192.168.2.68")).HostName;
if (sender.Contains("."))
sender = sender.Remove(sender.IndexOf('.'));
//MessageBox.Show("message received from : " + sender);
content = sender + ":" + content;
OnDataReceived(content.Replace("<EOF>", ""));
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
catch (Exception)
{
;
}
}
Send Method
private void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.Unicode.GetBytes(data);

// Begin sending the data to the remote device.


//BeginSend-Sends data asynchronously to a connected Socket.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}


SendCallback Method

private void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;

// Complete sending the data to the remote device.
//EndSend- end a pending Asynchronous send request

int bytesSent = handler.EndSend(ar);
//Shutdown-disable the send and receive on
handler.Shutdown(SocketShutdown.Both);
Ststem.Net.Socket.Socket
handler.Close();

}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

After designing SertverPart I Add a new clasas to this classlibrary and renamed new class as AsynchronousClient.
This is constructor of Client Class
public AsynchronousClient(String host, int p, String m)
{
hostName = host;
port = p;
message = m;
}
I pass remote hostname, port no, and message to be send as parameter to this class.


//StartClient method .. this method will start the specified client by //creating a socket with specified remote host address and port.
//The socket object client also specify which protocol is used and //which type of data is being sent.

public void StartClient()
{
try
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(hostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);

// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
// wait here for sometime...after connection go ahead
// if line is thr....wont notify about server not runnig
// if line is not thr....may send message before conncting
connectDone.WaitOne(1000, false);

// Send test data to the remote device.
Send(client, message + "<EOF>");
sendDone.WaitOne();

// Receive the response from the remote device.
Receive(client);
//receiveDone.WaitOne();

MessageBox.Show("Data received\n" + response);
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (SocketException)
{
MessageBox.Show("Server is not running at " + hostName + "'s end!!", "Error");
//MessageBox.Show(e.ToString());
}
catch (Exception)
{
MessageBox.Show("Error while sending message!!", "Error");
}
}


ConnectCallback Method
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// Signal that the connection has been made.
connectDone.Set();
MessageBox.Show("ConnectCallBack ");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Receive Method

private void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;

// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
MessageBox.Show("Receive..");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

ReceiveCallback Method

private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);

if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
MessageBox.Show("ReceiveCallback..");
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
MessageBox.Show(response);
}
receiveDone.Set();
MessageBox.Show("ReceiveCallback..");
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
Send Method

private void Send(Socket client, String data)
{
byte[] byteData = Encoding.Unicode.GetBytes(data);
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
MessageBox.Show("Send..");
}

SendCallback Method

private void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
sendDone.Set();
MessageBox.Show("SendCallback..");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}

After creating two classes ServerSocketListner and AsynchronousClient next aim is to create a class which will be used for containing methods defination for senddatato() and sendfileto() methods.
Also in addition to these methods this class will contain a method IsserverRunning(), with the help of this method we will be able to check whether Server is running or not , The return type of this method will be boolean.

This is SendReceiveHelper Class..In divide this class in two regions one is client region and second is server region.
In Client Region I declared two method and name them SenddataTo()
And SedFileTo().
The SendDataTo() method will send text message to specified host and port no.SendFileTo() method will send File to specified port and address.


public class SendReceiveHelper
{
#region Client part
/// <summary>
/// this function sends "data" to remote hostName....data is encoded message
/// </summary>
/// <param name="hostName">remote machine name</param>
/// <param name="port">port number of remote machine</param>
/// <param name="message">message to send</param>
public void SendDataTo(string hostName, int port, string message)
{
try
{
string FormattedMessage = MessageParser.EncodeMessage("message", message);
AsynchronousClient sockClient = new AsynchronousClient(hostName, port, FormattedMessage);
// if node is up but server not running at specified port ???????????????????
sockClient.StartClient();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}

/// <summary>
///
/// </summary>
/// <param name="hostName"></param>
/// <param name="port"></param>
/// <param name="message">filename with file content separated by ','</param>
public void SendFileTo(string hostName, int port, string message)
{
try
{
string FormattedMessage = MessageParser.EncodeMessage("file", message);
AsynchronousClient sockClient = new AsynchronousClient(hostName, port, FormattedMessage);
// if node is up but server not running at specified port ???????????????????
sockClient.StartClient();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static bool isServerRunning(String hostname)
{
try
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
new ManualResetEvent(false).WaitOne(100, true);
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (SocketException e)
{
MessageBox.Show(e.Message, hostname);
//Console.WriteLine(e.Message);
//Thread.Sleep(100);
return false;
}
return true;
}

#endregion


#region Server part
/// <summary>
/// delegate prototype
/// </summary>
public delegate void MessageReceivedCallback(string hostName, string messageType, string message);
/// <summary>
/// delegate function of type "MessageReceivedCallback"
/// </summary>
public static MessageReceivedCallback OnMessageReceived;
// listen on port 11000
public void StartServer()
{
int port = 11000;
AsynchronousSocketListener SockListener = new AsynchronousSocketListener(port);
SockListener.OnDataReceived = new AsynchronousSocketListener.DataReceivedCallback(OnDataReceived);
SockListener.StartListening();
}

/// <summary>
/// called when server receives any data
/// which then callbacks OnMessageReceived to inform GUI
/// </summary>
/// <param name="data"></param>

public void OnDataReceived(String data)
{
try
{
string[] parsedMessage = MessageParser.ParseMessage(data);
OnMessageReceived(parsedMessage[0], parsedMessage[1], parsedMessage[2]);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
//MessageBox.Show(e.ToString(), "error");
}
}
#endregion
}

This conversation is currently closed to new comments.

0 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Back to Windows Forum
0 total posts (Page 1 of 1)  

Related Discussions

Related Forums