WPF下的一个Socket

简介: public class Connection { Socket _connection; public Connection(Socket socket) { _connection = soc...

 

public class Connection
    {
        Socket _connection;

        public Connection(Socket socket)
        {
            _connection = socket;
        }

        public void WaitForSendData()
        {
            while (true)
            {
                byte[] bytes = new byte[1024];
                string data = "";

                //等待接收消息
                int bytesRec = this._connection.Receive(bytes);

                if (bytesRec == 0)
                {
                    ReceiveText("客户端[" + _connection.RemoteEndPoint.ToString() + "]连接关闭...");
                    break;
                }

                data += Encoding.UTF8.GetString(bytes, 0, bytesRec);
                ReceiveText("收到消息:" + data);

                string sendStr = "服务端已经收到信息!";
                byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                _connection.Send(bs, bs.Length, 0);
            }
        }

        public delegate void ReceiveTextHandler(string text);
        public event ReceiveTextHandler ReceiveTextEvent;
        private void ReceiveText(string text)
        {
            if (ReceiveTextEvent != null)
            {
                ReceiveTextEvent(text);
            }
        }
    }

 

 

public class SocketListener
    {
        public Hashtable Connection = new Hashtable();

        public void StartListen()
        {
            try
            {
                //端口号、IP地址
                int port = 2000;
                string host = "127.0.0.1";
                IPAddress ip = IPAddress.Parse(host);
                IPEndPoint ipe = new IPEndPoint(ip, port);

                //创建一个Socket类
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.Bind(ipe);//绑定2000端口
                s.Listen(0);//开始监听

                ReceiveText("启动Socket监听...");

                while (true)
                {
                    Socket connectionSocket = s.Accept();//为新建连接创建新的Socket

                    ReceiveText("客户端[" + connectionSocket.RemoteEndPoint.ToString() + "]连接已建立...");

                    Connection gpsCn = new Connection(connectionSocket);
                    gpsCn.ReceiveTextEvent += new Connection.ReceiveTextHandler(ReceiveText);

                    Connection.Add(connectionSocket.RemoteEndPoint.ToString(), gpsCn);

                    //在新线程中启动新的socket连接,每个socket等待,并保持连接
                    Thread thread = new Thread(new ThreadStart(gpsCn.WaitForSendData));
                    thread.Name = connectionSocket.RemoteEndPoint.ToString();
                    thread.Start();
                }
            }
            catch (ArgumentNullException ex1)
            {
                ReceiveText("ArgumentNullException:" + ex1);
            }
            catch (SocketException ex2)
            {
                ReceiveText("SocketException:" + ex2);
            }
        }

        public delegate void ReceiveTextHandler(string text);
        public event ReceiveTextHandler ReceiveTextEvent;
        private void ReceiveText(string text)
        {
            if (ReceiveTextEvent != null)
            {
                ReceiveTextEvent(text);
            }
        }
    }

 

 /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SocketListener listener;
        public MainWindow()
        {
            InitializeComponent();

            InitServer();
        }

        private void InitServer()
        {
            System.Timers.Timer t = new System.Timers.Timer(2000);
            //实例化Timer类,设置间隔时间为5000毫秒;
            t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
            //到达时间的时候执行事件; 
            t.AutoReset = true;
            t.Start();
        }

        private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (listener != null && listener.Connection != null)
            {
                //label2.Content = listener.Connection.Count.ToString();
                ShowText("连接数:" + listener.Connection.Count.ToString());
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(new ThreadStart(SocketListen));
            th.Start();
        }

        private void SocketListen()
        {
            listener = new SocketListener();
            listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
            listener.StartListen();
        }

        public delegate void ShowTextHandler(string text);
        ShowTextHandler setText;

        private void ShowText(string text)
        {
            if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
            {
                if (setText == null)
                {
                    setText = new ShowTextHandler(ShowText);
                }
                txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
            }
            else
            {
                txtSocketInfo.AppendText(text + "\n");
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ClientWindow client = new ClientWindow();
            client.Show();
        }
    }

 

 

 

 /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        SocketListener listener;
        public MainWindow()
        {
            InitializeComponent();

            InitServer();
        }

        private void InitServer()
        {
            System.Timers.Timer t = new System.Timers.Timer(2000);
            //实例化Timer类,设置间隔时间为5000毫秒;
            t.Elapsed += new System.Timers.ElapsedEventHandler(CheckListen);
            //到达时间的时候执行事件; 
            t.AutoReset = true;
            t.Start();
        }

        private void CheckListen(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (listener != null && listener.Connection != null)
            {
                //label2.Content = listener.Connection.Count.ToString();
                ShowText("连接数:" + listener.Connection.Count.ToString());
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Thread th = new Thread(new ThreadStart(SocketListen));
            th.Start();
        }

        private void SocketListen()
        {
            listener = new SocketListener();
            listener.ReceiveTextEvent += new SocketListener.ReceiveTextHandler(ShowText);
            listener.StartListen();
        }

        public delegate void ShowTextHandler(string text);
        ShowTextHandler setText;

        private void ShowText(string text)
        {
            if (System.Threading.Thread.CurrentThread != txtSocketInfo.Dispatcher.Thread)
            {
                if (setText == null)
                {
                    setText = new ShowTextHandler(ShowText);
                }
                txtSocketInfo.Dispatcher.BeginInvoke(setText, DispatcherPriority.Normal, new string[] { text });
            }
            else
            {
                txtSocketInfo.AppendText(text + "\n");
            }
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            ClientWindow client = new ClientWindow();
            client.Show();
        }
    }

 

 

 

相关文章
|
C# Windows
wpf怎么使用WindowsFormsHost(即winform控件)
原文:wpf怎么使用WindowsFormsHost(即winform控件) 使用方法:   1、首先,我们需要向项目中的引用(reference)中添加两个动态库dll,一个是.
5161 0
WPF使用DataGridComboBoxColumn完成绑定
 在使用DataGrid的时候,有时候需要使某些列为ComboBox,这时自然想到使用DataGridComboBoxColumn,但是如果使用的是ItemsSource数据绑定后台的对象,就会发现,这根本就不能用。
2045 0
|
C# 容器
在WPF中使用winform控件WebBrowser
在WPF中使用winform控件WebBrowser
|
C#
WPF中StringFormat的用法
原文:WPF中StringFormat的用法 WPF中StringFormat的用法可以参照C#中string.Format的用法 1、 C#中用法: 格式化货币(跟系统的环境有关,中文系统默认格式化人民币,英文系统格式化美元)示例: string.
4122 0
|
C# UED
WPF 使用DMSkin for WPF 快速搭建漂亮的WPF程序
原文:WPF 使用DMSkin for WPF 快速搭建漂亮的WPF程序 DMSkin-for-WPF是一个基于WPF的.Net WPF开源界面库,实现了无边框的WPF开发方案,内置部分控件模板. 你可以参照模板自行修改完善。
2020 0
|
C#
WPF 获得DataGridRow和 DataGridCell的方法
原文:WPF 获得DataGridRow和 DataGridCell的方法 原文地址 简介   在WPF中,DataGrid控件并没有提供访问其DataGridRow或者DataGridCell的方法。
2021 0
|
C# 容器
在WPF中使用WinForm控件方法
原文:在WPF中使用WinForm控件方法 1、      首先添加对如下两个dll文件的引用:WindowsFormsIntegration.dll,System.Windows.Forms.dll。
1198 0
|
C#
WPF ChangePropertyAction中TargetName和TargetObject的区别
原文:WPF ChangePropertyAction中TargetName和TargetObject的区别 在wpf页面布局中经常用到ChangePropertyAction来更改属性,在这个里面有TargetName和TargetObject两个属性,都表示需要修改的控件名称,那么这两个有什么区...
879 0
|
C# API
WPF关闭应用汇总
原文:WPF关闭应用汇总 就本人而言,C#中关闭应用主要有以下途径: 1.Close():关闭当前窗口,可以在OnClosing和 OnClosed中捕获消息,在OnClosing的时候,可以取消关闭窗口 2.
1148 0
|
C#
在Winform窗体中使用WPF控件(附源码)
原文:在Winform窗体中使用WPF控件(附源码) 今天是礼拜6,下雨,没有外出,闲暇就写一篇博文讲下如何在Winform中使用WPF控件。原有是我在百度上搜索相关信息无果,遂干脆动手自己实现。 WPF控件的漂亮是Winform无法匹及的,本文主旨是在Winform工程中如何使用WPF控件。
1820 0