|
using System;
using System.Data;
using System.Configuration;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using System.Security.Principal;
using Common;
/// <summary>
/// Summary description for ClientApplication
///This class is used to create an asynchronous client socket.
///Asynchronous sockets use multiple threads from the system thread pool
/// to process network connections. One thread is responsible for initiating
/// the sending or receiving of data; other threads complete the connection
/// to the network device and send or receive the data.
/// </summary>
namespace Common
{
public class ClientApplication
{
private const int defaultPort = 11000;
private static int port;
private static IPAddress ipAddress;
private const string endOfData = "<EOF>";
private static LingerOption lingerOption = new LingerOption(true, 1);
// ManualResetEvent instances signal completion.
public ManualResetEvent connectDone =
new ManualResetEvent(false);
public ManualResetEvent sendDone =
new ManualResetEvent(false);
public ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private byte[] responseData;
private Socket client = null;
private static Mutex mut = new Mutex(false);
public ClientApplication()
{
}
public byte[] ResponseData
{
get { return responseData; }
set { responseData = value; }
}
public Boolean Initialize()
{
Boolean retVal = true;
try
{
string ip = "127.0.0.1";
ipAddress = IPAddress.Parse(ip);
port = 11000;
}
catch (Exception e)
{
retVal = false;
}
finally
{
}
return retVal;
}
public Boolean StartClient()
{
// Connect to a remote device.
Boolean retVal = true;
try
{
// Establish the remote endpoint for the socket.
//IPHostEntry ipHostInfo = Dns.Resolve("vinitabatra.raireki.umbrella");
//IPAddress ipAddress = ipHostInfo.AddressList[0];
Boolean res = Initialize();
if (res)
{
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
}
}
catch (Exception e)
{
retVal = false;
connectDone.Set();
}
finally
{
}
return retVal;
}
public void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
connectDone.Set();
}
finally
{
}
}
public void Receive()
{
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);
}
catch (Exception e)
{
receiveDone.Set();
}
finally
{
}
}
public void ReceiveCallback(IAsyncResult ar)
{
String content = String.Empty;
try
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
Console.WriteLine("before EndReceive");
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.Unicode.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
int index = -1;
index = content.LastIndexOf("<EOF>");
//if (content.IndexOf("<EOF>") != -1)
if (index != -1)
{
// All the data has been read from the server.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
content = content.Remove(index);
responseData = Encoding.Unicode.GetBytes(content);
receiveDone.Set();
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
}
catch (Exception e)
{
receiveDone.Set();
}
finally
{
}
}
public void Send(ref byte[] requestData)
{
try
{
if (requestData.Length > 0)
{
Console.WriteLine("send function called");
String temp = Encoding.Unicode.GetString(requestData);
temp = String.Concat(temp, endOfData);
requestData = Encoding.Unicode.GetBytes(temp);
//Begin sending the data to the remote device.
client.BeginSend(requestData, 0, requestData.Length, 0,
new AsyncCallback(SendCallback), client);
}
}
catch (Exception e)
{
sendDone.Set();
}
finally
{
}
}
public void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
sendDone.Set();
}
finally
{
}
}
public void CloseSocket()
{
try
{
Thread.Sleep(10);
client.Shutdown(SocketShutdown.Both);
client.Close();
}
catch (Exception e)
{
}
finally
{
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.