zoukankan      html  css  js  c++  java
  • C#网络Socket的数据发送与接收处理(利用异步)的模板(模式)

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Sockets;
    using System.Net;
    using System.Windows.Forms;


    namespace SocketClient
    {
        /// <summary>
        /// C#网络Socket的数据发送与接收处理(利用异步)的模板(模式)
        /// </summary>
        class test_Socket
        {
            Socket m_Socket;
            /// <summary>
            /// C#网络Socket的数据发送与接收处理(利用异步)
            /// </summary>
            /// <param name="_ip">要连接的IP</param>
            /// <param name="_Port">对方开放的端口</param>
            public void Net_Socket_Send_Receive(string _ip,int _Port)
            {
                IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(_ip), _Port);
                m_Socket=new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                Byte[] buffer = new Byte[1024];
                m_Socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
                byte[] recvBytes = new byte[20];
                m_Socket.BeginReceive(recvBytes, 0, recvBytes.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);


            }
            private void OnSend(IAsyncResult ar)
            {
                try
                {
                    
                    m_Socket.EndSend(ar);
                }
                catch (ObjectDisposedException)
                { }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Send: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }


            private void OnReceive(IAsyncResult ar)
            {
                try
                {
                    m_Socket.EndReceive(ar);


                }
                catch (ObjectDisposedException)
                { }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Receive: ", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }

  • 相关阅读:
    【译】.NET 的新的动态检测分析
    【译】Visual Studio 的 Razor 编辑器的改进
    【译】.NET 5. 0 中 Windows Form 的新特性
    MySQL InnoDB 索引(Index)
    MySQL 全文检索(Full-Text Search)
    MySQL 计算最大值、最小值和中位数
    MySQL 触发器(Triggers)
    MySQL 视图(View)
    MySQL基础知识:MySQL String 字符串处理
    MySQL基础知识:MySQL Connection和Session
  • 原文地址:https://www.cnblogs.com/cyz1980/p/2972507.html
Copyright © 2011-2022 走看看