zoukankan      html  css  js  c++  java
  • 跨线程访问和服务器客户端访问互换(原创)

    Server:

    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Ink;
    using NetSockets;
    using System.Net;
    using System.IO;
    using System.Threading;
    using System.Windows.Threading;

    namespace InkServer
    {
        /// <summary>
        
    /// Interaction logic for MainWindow.xaml
        
    /// </summary>
        public partial class MainWindow : Window
        {
            NetObjectServer server = new NetObjectServer();

            Dictionary<string, NetObjectClient> clients = new Dictionary<string, NetObjectClient>();
            string strHost = "172.18.50.104";//104
            
    //"172.18.200.118";
            
    //string strHost = "172.18.200.118";
            
    //"172.18.200.118";
            int port = 11006;
            int callbackPort = 11007;

            public MainWindow()
            {
                InitializeComponent();

                server.EchoMode = NetEchoMode.EchoAllExceptSender;

                inkCanv.StrokeCollected+=new InkCanvasStrokeCollectedEventHandler(inkCanv_StrokeCollected);

                this.inkCanv.DefaultDrawingAttributes.StylusTip = StylusTip.Ellipse;
                this.inkCanv.DefaultDrawingAttributes.Width = 10;
                this.inkCanv.DefaultDrawingAttributes.Height = 10;
                this.inkCanv.EditingMode = InkCanvasEditingMode.Ink;

                server.OnReceived += new NetClientReceivedEventHandler<NetObject>(server_OnReceived);


                IPAddress ip = IPAddress.Parse(strHost);
                //Start the server
                server.Start(ip, port);



            }
            void client_OnReceived(object sender, NetReceivedEventArgs<NetObject> e)
            {
                //write("Client received" + e.Data.Name as string + e.Data.Object as string);
            }

            Thread th;

            void server_OnReceived(object sender, NetClientReceivedEventArgs<NetObject> e)
            {
                //Get the Clients IP
                if (e.Data.Object as string == "SendIP")
                {
                    string ip = e.Data.Name;
                    if (!clients.Keys.Contains(ip))
                    {
                        NetObjectClient noc = new NetObjectClient();
                        if (!noc.IsConnected)
                        {
                            noc.TryConnect(ip, callbackPort);
                        }
                        clients.Add(ip, noc);
                    }
                }


                if (e.Data.ByteArray!=null)
                OnInkStrokesUpdate(e.Data.ByteArray);

                //th = new Thread(new ParameterizedThreadStart(OnInkStrokesUpdate));
                
    //th.IsBackground = true;
                
    //th.Start(e.Data.ByteArray);

            }

            private delegate void UpdateDelegate(byte[] ds);
            //private delegate void UpdateDelegate(object ds);

            public void OnInkStrokesUpdate(object bytesStroke)
            {
                byte[] byts = bytesStroke as byte[];
                if (inkCanv != null)
                {
                    // Checking if this thread has access to the object.
                    if (inkCanv.Dispatcher.CheckAccess())
                    {
                        // This thread has access so it can update the UI thread.
                        InkStrokesUpdate(byts);
                    }
                    else
                    {
                        // This thread does not have access to the UI thread.
                        
    // Place the update method on the Dispatcher of the UI thread.
                        inkCanv.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new UpdateDelegate(InkStrokesUpdate), byts);
                    }
                }
            }

            public void OnInkStrokesUpdate(byte[] bytesStroke)
            {
                if (inkCanv != null)
                {
                    // Checking if this thread has access to the object.
                    if (inkCanv.Dispatcher.CheckAccess())
                    {
                        // This thread has access so it can update the UI thread.
                        InkStrokesUpdate(bytesStroke);
                        SaveStrokes();
                    }
                    else
                    {
                        // This thread does not have access to the UI thread.
                        
    // Place the update method on the Dispatcher of the UI thread.
                        inkCanv.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new UpdateDelegate(InkStrokesUpdate), bytesStroke);
                        SaveStrokes();
                    }
                }

                
            }

            private void InkStrokesUpdate(byte[] bytesStroke)
            {
                try
                {
                    System.IO.MemoryStream memoryStream = new MemoryStream(bytesStroke);
                    this.inkCanv.Strokes = new StrokeCollection(memoryStream);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }

            private delegate void SaveStrokesDelegate();


            private void SaveStrokes()
            {
                if (inkCanv != null)
                {
                    // Checking if this thread has access to the object.
                    if (inkCanv.Dispatcher.CheckAccess())
                    {
                        // This thread has access so it can update the UI thread.
                        SaveStrokesAndSend();
                    }
                    else
                    {
                        // This thread does not have access to the UI thread.
                        
    // Place the update method on the Dispatcher of the UI thread.
                        inkCanv.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new SaveStrokesDelegate(SaveStrokesAndSend));
                    }
                }

                try
                {

               }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message, Title);
                }
            }

            private void SaveStrokesAndSend()
            {
                MemoryStream memoryStream = new MemoryStream();

                this.inkCanv.Strokes.Save(memoryStream);
                //Connect to the server

                foreach (KeyValuePair<string, NetObjectClient> kv in clients)
                {
                    if (kv.Value.IsConnected)
                        kv.Value.Send("", memoryStream.GetBuffer());
                }

                memoryStream.Flush();
            }

            private void inkCanv_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
            {
                SaveStrokes();
            }

            private void Window_Closed(object sender, EventArgs e)
            {
                foreach (KeyValuePair<string, NetObjectClient> client in clients)
                {
                    client.Value.Disconnect();
                }
                server.Stop();
            }

        }
    }

    Client:

    View Code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.Windows.Ink;
    using NetSockets;
    using System.Net;
    using System.IO;
    using System.Threading;
    using System.Windows.Threading;

    namespace InkClient
    {
        /// <summary>
        
    /// Interaction logic for MainWindow.xaml
        
    /// </summary>
        public partial class MainWindow : Window
        {
            NetObjectServer server = new NetObjectServer();
            NetObjectClient client = new NetObjectClient();
            string strHost = "172.18.50.104";
            //132 大屏
            
    //104;
            
    //"172.18.200.118";
            
    //string strHost = "172.18.200.118";//"172.18.200.118";
            int port = 11006;
            int callbackPort = 11007;



            string IPself
            {
                get {
                    IPHostEntry IPHost = Dns.Resolve(Dns.GetHostName());
                    IPAddress[] address = IPHost.AddressList;
                    for (int i = 0; i < address.Count(); i++)
                    {
                        if (address[i].ToString().StartsWith("172.18.50"))
                        return address[i].ToString();
                    }
                    return "127.0.0.1";
                }
            }


            public MainWindow()
            {
                InitializeComponent();
                server.EchoMode = NetEchoMode.EchoAllExceptSender;

                
                inkCanv.StrokeCollected += new InkCanvasStrokeCollectedEventHandler(inkCanv_StrokeCollected);

                this.inkCanv.DefaultDrawingAttributes.StylusTip = StylusTip.Ellipse;
                this.inkCanv.DefaultDrawingAttributes.Width = 10;
                this.inkCanv.DefaultDrawingAttributes.Height = 10;
                this.inkCanv.EditingMode = InkCanvasEditingMode.Ink;

                server.OnReceived += new NetClientReceivedEventHandler<NetObject>(server_OnReceived);
                client.OnReceived += new NetReceivedEventHandler<NetObject>(client_OnReceived);


                IPAddress ipSelf = IPAddress.Parse(IPself);
                //Start the server
                server.Start(ipSelf, callbackPort);

                //Connect to the server
                client.TryConnect(strHost, port);

                //send IP to server
                client.Send(IPself, "SendIP");
            }

            void client_OnReceived(object sender, NetReceivedEventArgs<NetObject> e)
            {
                //write("Client received" + e.Data.Name as string + e.Data.Object as string);
                
    //OnInkStrokesUpdate(e.Data.ByteArray);

            }

            Thread thOnReceived;

            void server_OnReceived(object sender, NetClientReceivedEventArgs<NetObject> e)
            {
                OnInkStrokesUpdate(e.Data.ByteArray);

                //thOnReceived = new Thread(new ParameterizedThreadStart(OnInkStrokesUpdate));
                
    //thOnReceived.IsBackground = true;
                
    //thOnReceived.Start(e.Data.ByteArray);
            }

            private delegate void UpdateDelegate(byte[] ds);
            //private delegate void UpdateDelegate(object ds);

            public void OnInkStrokesUpdate(object bytesStroke)
            {
                byte[] byts = bytesStroke as byte[];
                if (inkCanv != null)
                {
                    // Checking if this thread has access to the object.
                    if (inkCanv.Dispatcher.CheckAccess())
                    {
                        // This thread has access so it can update the UI thread.
                        InkStrokesUpdate(byts);
                    }
                    else
                    {
                        // This thread does not have access to the UI thread.
                        
    // Place the update method on the Dispatcher of the UI thread.
                        inkCanv.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new UpdateDelegate(InkStrokesUpdate), byts);
                    }
                }
            }

            public void OnInkStrokesUpdate(byte[] bytesStroke)
            {
                if (inkCanv != null)
                {
                    // Checking if this thread has access to the object.
                    if (inkCanv.Dispatcher.CheckAccess())
                    {
                        // This thread has access so it can update the UI thread.
                        InkStrokesUpdate(bytesStroke);
                    }
                    else
                    {
                        // This thread does not have access to the UI thread.
                        
    // Place the update method on the Dispatcher of the UI thread.
                        inkCanv.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                            new UpdateDelegate(InkStrokesUpdate), bytesStroke);
                    }
                }


            }

            private void InkStrokesUpdate(byte[] bytesStroke)
            {
                try
                {
                    System.IO.MemoryStream memoryStream = new MemoryStream(bytesStroke);
                    this.inkCanv.Strokes = new StrokeCollection(memoryStream);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
            }

            private void SaveStrokes()
            {
                try
                {
                    MemoryStream memoryStream = new MemoryStream();

                    this.inkCanv.Strokes.Save(memoryStream);


                    if (client.IsConnected)
                        client.Send("", memoryStream.GetBuffer());

                    memoryStream.Flush();

                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message, Title);
                }
            }
            Thread th;
            private void inkCanv_StrokeCollected(object sender, InkCanvasStrokeCollectedEventArgs e)
            {
                SaveStrokes();
                //th = new Thread(new ThreadStart(SaveStrokes));
                
    //th.IsBackground = true;
                
    //th.Start();
            }

            private void Window_Closed(object sender, EventArgs e)
            {
                client.Disconnect();
                server.Stop();
            }
        }
    }
    关于作者: 王昕(QQ:475660) 在广州工作生活30余年。十多年开发经验,在Java、即时通讯、NoSQL、BPM、大数据等领域较有经验。
    目前维护的开源产品:https://gitee.com/475660
  • 相关阅读:
    HTMLElement.dataset
    toLocaleString
    export,import ,export default是什么
    css鼠标禁用
    npm ERR! cb() never called! npm ERR! This is an error with npm itself.错误解决办法
    vue3的新特性
    el-dialog开启拖拽功能
    yarn config get registry
    JS中的函数防抖
    注入攻击的解决思路
  • 原文地址:https://www.cnblogs.com/starcrm/p/2191828.html
Copyright © 2011-2022 走看看