|
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Common;
using System.IO;
using System.Runtime.InteropServices;
//This program creates a server that receives connection requests
//from clients. The server is built with an asynchronous socket,
//so execution of the server application is not suspended
//while it waits for a connection from a client.
//The client which sends the request to this server is VSTO addin.
//If VSTO addin finds that the DocumentID is removed,
//it re-adds the same ID in the office file by sending the request to this server.
namespace SocketServer
{
public class ServerApplication
{
public const int STRINGDATA_DOCUMENTID = 100;
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private const int queueSize = 10;
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);
public static Boolean Initialize()
{
Boolean retVal = true;
try
{
string ip = "127.0.0.1";
ipAddress = IPAddress.Parse(ip);
port = 11000;
}
catch (Exception e)
{
}
return retVal;
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
//IPAddress ipAddress = ipHostInfo.AddressList[0];
try
{
Boolean res = Initialize();
if (res)
{
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(queueSize);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
while (true)
{
// Set the event to nonsignaled state.
connectDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
connectDone.WaitOne();
}
}
}
catch (Exception e)
{
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
try
{
connectDone.Set();
Console.WriteLine("AcceptCallback...");
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
handler.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
Receive(handler);
}
catch (Exception e)
{
}
}
public static void Receive(Socket handler)
{
try
{
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
}
}
public static void ReceiveCallback(IAsyncResult ar)
{
try
{
String content = String.Empty;
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;
index = content.LastIndexOf("<EOF>");
if (index != -1)
{
Byte[] requestData = Encoding.Unicode.GetBytes(content);
doWork(ref requestData, handler);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.bufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
}
catch (Exception e)
{
}
}
private static void AddDocumentID(Common.Message message)
{
//bool fileOpened = false;
//FileStream fstream = null;
//fileOpened = GetFileHandle(message.fileName, ref fstream);
//Adds the DocumentID in the file specified by message.fileName by calling
//fileOperation.AddData()
//FileOperation class is present in assembly Common
//Common library is created by project named Common
//See the references in solution explorer
//It shows Common is added as c# library in this project.
//if (!fileOpened)
//{
// return;
//}
//else
//{
FileOperation fileOperation = new FileOperation();
// if (fstream != null)
// fstream.Close();
// Microsoft.Win32.SafeHandles.SafeFileHandle handle = fstream.SafeFileHandle;
// handle.
bool success = fileOperation.AddData(message.fileName, STRINGDATA_DOCUMENTID, message.documentID);
Console.WriteLine("success {0}", success);
DocumentInfoHandler documentInfoHandler = new DocumentInfoHandler();
documentInfoHandler.DeleteDocumentInfo(message.uniqueID);
//}
}
private static void doWork(ref byte[] data, Socket handler)
{
//This function deserializes the message received from client application
//and calls AddDocumentID() to add document ID
byte[] responseData = null;
try
{
Common.Message message = null;
Serialization serialization = new Serialization();
Boolean res = false;
res=serialization.Deserialize(ref data, ref message);
if ((res == true) && (message != null))
{
Console.WriteLine("deserailization successfull");
AddDocumentID(message);
}
else
{
Console.WriteLine("deserailization failed");
}
}
catch (Exception e)
{
}
finally
{
}
}
private static bool GetFileHandle(string fileFullPath, ref FileStream fStream)
{
// This funtion tries to capture the file handle as soon as
//it is freed by other process.
bool success = false;
int totalTry = 1;
while(true)
{
try
{
fStream = File.Open(fileFullPath, FileMode.Open,FileAccess.Read,FileShare.None);
//fStream.
// fStream.Close();
success = true;
break;
}
catch (Exception exp)
{
Thread.Sleep(100);
}
}
Console.WriteLine("File Handle cpatured");
return success;
}
private static void Send(Socket handler, ref byte[] responseData)
{
try
{
if (responseData.Length > 0)
{
Console.WriteLine("send function called");
String temp = Encoding.Unicode.GetString(responseData);
temp = String.Concat(temp, endOfData);
responseData = Encoding.Unicode.GetBytes(temp);
//Begin sending the data to the remote device.
handler.BeginSend(responseData, 0, responseData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
}
catch (Exception e)
{
}
}
public static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
}
}
public static void Main()
{
StartListening();
}
}
}
|
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.