Articles
FAQs
Login
Communication between Client and Server using IPC
By Perry
Access over 40 UI widgets with everything from interactive menus to rich charts.
Use this sample code which can make communication between Client and Server using IPC.
SharedInterface namespace will be the reference added in both the Client and Server project. To run this project start the Server first and then run the client. Client will send message to server and server will send the same message to client as an acknoledgement.
SharedInterface.cs
=============
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
#endregion
namespace SharedInterface
{
public interface ISharedChannle
{
void SendMessage(string message, string sender);
}
}
Client.cs
======
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using SharedInterface;
#endregion
namespace Client
{
class Program
{
static void Main(string[] args)
{
IpcChannel ipc = new IpcChannel("MessageClient");
ChannelServices.RegisterChannel(ipc);
ISharedChannle sm = (ISharedChannle)Activator.GetObject(typeof(ISharedChannle),
"ipc://MessageServer/MessageServer.rem");
if (sm == null)
{
Console.WriteLine("Failed to communicate with remote server.");
return;
}
string message = "Hi..how r u";
string sender = "username";
try
{
sm.SendMessage(message, sender);
}
catch(Exception ex)
{
System.Console.WriteLine(ex.Message);
System.Console.Read();
}
}
}
}
Server.cs
======
#region Using directives
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
#endregion
namespace Server
{
public delegate void OnMessageReceivedDelegate(string message, string sender);
public class SharedMessage : MarshalByRefObject, SharedInterface.ISharedChannle
{
public event OnMessageReceivedDelegate OnMessageReceived;
public void SendMessage(string message, string sender)
{
if ((OnMessageReceived != null) &&
(OnMessageReceived.GetInvocationList().Length > 0))
{
System.Console.WriteLine("Message Came");
System.Console.Read();
OnMessageReceived(message, sender);
}
}
}
}
Regards,
Megha
Popularity
(
1929 Views
)