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);
                }
            }
        }
    }

  • 相关阅读:
    static的全部用法收集整理
    文思创新复试及一些自己的思考
    “一碗牛肉面”引发的管理难题
    信必优面试实录
    我做PM(项目经理)这段时间...
    什么是面向对象?
    沟通
    体会Bind和Eval的不同用法
    北京艾德思奇科技有限公司面试实录
    今天去sony公司面试实录
  • 原文地址:https://www.cnblogs.com/cyz1980/p/2972507.html
Copyright © 2011-2022 走看看