• WPF下的一个Socket


    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 + "
    ");
                }
            }
    
            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 + "
    ");
                }
            }
    
            private void button2_Click(object sender, RoutedEventArgs e)
            {
                ClientWindow client = new ClientWindow();
                client.Show();
            }
        }
  • 相关阅读:
    阿里应该不应该给公众一个交代——教师使用钉钉上网课“遭黑客攻击网暴”后死亡
    tensorflow1.x——如何在C++多线程中调用同一个session会话
    偶然间发现一个还不错的仪表盘界面——感觉很不错的界面设计
    国产深度学习框架MindSpore的高校发展之旅——“样本点”计划
    记录一次实验室linux系统的GPU服务器死机故障的排查——Linux系统的Power States
    tensorflow1.x——如何在python多线程中调用同一个session会话
    对欠曝光图片的处理
    如何使用git通过ssh协议拉取gitee上的项目代码——如何正确的免密使用git
    再用国产操作系统deepin出现拖影现象
    记录一次实验室linux系统的GPU服务器死机排查过程——某显卡满负荷导致内核进程超时导致系统死机
  • 原文地址:https://www.cnblogs.com/zuiyirenjian/p/3358770.html
Copyright © 2020-2023  润新知