C#: socket同步通讯与异步通讯

1. socket同步通讯:

            Socket m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_socket.Connect(m_ipEnd);
            m_socket.Send(buf_send, (int)m_len, SocketFlags.None);
            m_socket.Receive(buf_recv, (int)m_len, SocketFlags.None);
            m_socket.Close();

2. socket异步通讯

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Collections;

 namespace WinSocketAsync
{
    public partial class FormMain : Form
    {
        public Socket m_socket;
        public IPEndPoint m_iep;
        Queue m_qSend = new Queue();
        Queue m_qRecv = new Queue();

        int m_interval;         //发送间隔
        int m_DataLen;          //数据长度
        ulong m_curSendCount;   //当前发送次数
        ulong m_curRecvCount;   //当前接收次数
        ulong m_curSendBit;     //当前发送位数
        ulong m_curRecvBit;     //当前接收位数
        ulong m_curRightBit;    //当前正确位数
        ulong m_curErrorBit;    //当前错误位数
        byte[][] m_senddata;     //发送的数据包

        delegate void DGTextBox(string str);
        delegate void DGButton(bool b);

        public class StateObject : Object
        {
            public Socket socket;
            public byte[] buffer;
        }

        public FormMain()
        {
            InitializeComponent();
            //m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName. )
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            TCurTime_Tick(sender, e);

            m_interval = int.Parse(TBinterval.Text.Trim());
            m_DataLen = int.Parse(TBDataLen.Text.Trim());

            m_senddata = new byte[256][];
            Random rd = new Random();
            for (int i = 0; i < 256; i++)
            {
                m_senddata[i] = new byte[m_DataLen];
                for (int j = 0; j < m_DataLen; j++)
                {
                    m_senddata[i][j] = (byte)rd.Next(1, 255);
                }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (m_socket == null)
            {
                return;
            }

            if (m_socket.Connected)
            {
                m_socket.Shutdown(SocketShutdown.Receive);
                m_socket.Close();
            }
        }

        private void TBinterval_TextChanged(object sender, EventArgs e)
       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值