Share data on the clipboard using P2P in WCF

Source: Internet
Author: User

WCF and P2P

WCF is used to implement data communication. In this article. I will lead everyone into the P2P world of WCF. An instance indicates that P2P is used in WCF.

First, let's know what P2P is. For details, see P2P. Here, based on my understanding, I will briefly describe it in combination with WCF. Generally, you can use a server as the intermediate station for client-to-client interaction. The client transmits the data to the server, and the server forwards the data to other clients. Obviously, this increases the burden on the server. P2P solves this problem. Each client can be a client that accepts data and a server that uploads data. With PPS and thunder, you can easily understand the two software. They both need to upload data and download data. See the following two figures:

 

Figure 1: Redirection around the central server

 

Figure 2: P2P Distribution

Instance features

In my example, there are many computers in a LAN. When one of the computers implements copy or cut, the copied and cut data will be displayed on other computers. You can implement Ctrl + C or Ctrl + X to copy or cut the data. On other computers, there is a form that specifically displays the data you copy or cut (limited to text data ).

There are two difficulties in implementing this program:

1. How to listen to Ctrl + C or Ctrl + X

2. You do not need a specific server (do not use WCF duplex communication). If you use P2P to implement data communication.

Instance implementation:

The following describes the implementation based on these two difficulties.

I. event listening:

1. In Windows form applications, the protected override void WndProc (ref System. Windows. Forms. Message m) method can be reloaded for event listening. Judge the number of the Message. If it is a copy or clipboard event. We will broadcast information in the Clipboard through the P2P service of WCF. The Code is as follows:

        protected override void WndProc(ref System.Windows.Forms.Message m)        {            // defined in winuser.h            const int WM_DRAWCLIPBOARD = 0x308;            const int WM_CHANGECBCHAIN = 0x030D;            switch (m.Msg)            {                case WM_DRAWCLIPBOARD:                    DisplayClipboardData();                    SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);                    break;                case WM_CHANGECBCHAIN:                    if (m.WParam == nextClipboardViewer)                        nextClipboardViewer = m.LParam;                    else                        SendMessage(nextClipboardViewer, m.Msg, m.WParam, m.LParam);                    break;                default:                    base.WndProc(ref m);                    break;            }        }

2. submit it to User32.dll for processing:

        [DllImport("User32.dll")]        protected static extern int SetClipboardViewer(int hWndNewViewer);        [DllImport("User32.dll", CharSet = CharSet.Auto)]        public static extern bool ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext);        [DllImport("user32.dll", CharSet = CharSet.Auto)]        public static extern int SendMessage(IntPtr hwnd, int wMsg, IntPtr wParam, IntPtr lParam);

The above code solves the first problem: how to listen to Ctrl + C or Ctrl + X events.

2. In WCF, we need to implement P2P through NetPeerTcpBinding.

Next I will implement this P2P application service step by step.

1. define and implement a contract:

   [ServiceContract(CallbackContract = typeof(IShare))]    public interface IShare    {       [OperationContract(IsOneWay = true)]       void ShareClipboard(string type,string message);    }
Public class implements implementation: IShare {private static Form m_receiverForm; private static ClipEventHandler m_OnClipReceive; public void sharsponboard (string type, string message) {try {retry (m_OnClipReceive, type, message );} catch (Exception e) {MessageBox. show (e. toString () ;}} public void SetForm (Form form, ClipEventHandler theCallback) {m_receiverForm = form; m_OnClipReceive = theCallback;} use a class to manage this service:
    public class Peer    {        public string Id { get; private set; }        public IShare Channel;        public ShareImplementation Host;        public ClipEventHandler clipeventhandler;        public Form form;        public Peer(string id)        {            Id = id;        }        private DuplexChannelFactory<IShare> _factory;           public void StartService()    {        var binding = new NetPeerTcpBinding();        binding.Security.Mode = SecurityMode.None;         var endpoint = new ServiceEndpoint(            ContractDescription.GetContract(typeof(IShare)),            binding,            new EndpointAddress("net.p2p://SimpleP2P"));        Host = new ShareImplementation();        Host.SetForm(form,clipeventhandler);        _factory = new DuplexChannelFactory<IShare>(new InstanceContext(Host), endpoint);         var channel = _factory.CreateChannel();         ((ICommunicationObject)channel).Open();         // wait until after the channel is open to allow access.        Channel = channel;    }    public void StopService()    {        ((ICommunicationObject)Channel).Close();        if (_factory != null)            _factory.Close();    }    private readonly AutoResetEvent _stopFlag = new AutoResetEvent(false);    public void Run()    {        Console.WriteLine("[ Starting Service ]");        StartService();        Console.WriteLine("[ Service Started ]");        _stopFlag.WaitOne();        Console.WriteLine("[ Stopping Service ]");        StopService();        Console.WriteLine("[ Service Stopped ]");    }    public void Stop()    {        _stopFlag.Set();    }    }

In WindowsForm, the service is called using the DisplayClipboardData () method. The Code is as follows.
        void DisplayClipboardData()        {            try            {                IDataObject iData = new DataObject();                string type = "",message="";                              iData = Clipboard.GetDataObject();                if (Clipboard.ContainsText())                {                    message = (string)iData.GetData(DataFormats.Text);                }                          if (peer != null && peer.Channel != null)                {                    peer.Channel.ShareClipboard("text", message);                }            }            catch (Exception e)            {                MessageBox.Show(e.ToString());            }        }
There is also a method to accept the Information Method AddToClip, the Code is as follows:
        public void AddToClip(string type, string message)        {            if (type == "rtf")            {                IDataObject iData = new DataObject(DataFormats.Rtf, message);                richTextBox1.Rtf = (string)iData.GetData(DataFormats.Rtf);                //richTextBox1.Rtf = message;            }            else if (type == "text")                richTextBox1.Text = message;            else                richTextBox1.Text = "[Clipboard data is not RTF or ASCII Text]";            richTextBox1.Text = message;        }

Since the main thread of WCF to reconcile windows form is not one, a delegate is used:

    public delegate void ClipEventHandler(string type ,string clipData);

For more information, see the code.

Instance effect:

Copy text data on zhuqilin

Display the data copied on zhuqilin on the computer Colin:

Summary:

Last week, I used the WCF duplex to implement an audio chat room program. Some Garden Friends proposed P2P video, voice, and chat to achieve better efficiency and performance, so they studied the P2P of WCF. This article is a simple example of WCF P2P.

Extension:

This article only supports sharing the text clipboard. If you are interested, you can expand it further.

Extension 1:Data is directly transferred to the clipboard of another computer. You can press Ctrl + V to paste the data.

Extension 2:Now we only share the text clipboard. It can be expanded to files, videos, and images.

The result can be: if the two ends of the LAN are shared with the clipboard. Copy files on machine A and paste them directly on machine B.

This example is inspired by RealVNC. Kids shoes who have used RealVNC know that, whether on the LAN or the Internet, they can share the data on the clipboard as long as the two PCs are connected.

Finally:It takes time to create P2P and open a P2P pipeline. Therefore, after running this program, you must wait for a while before sharing your clipboard. If you have any suggestions, please leave a message. If you have any help, please recommend them. Thx.

Code: http://files.cnblogs.com/zhuqil/ShareClipboard.rar

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.