日期:2014-05-17  浏览次数:21045 次

C#Socket异步通信在处理批量并发时有时出现数据重叠
代码如下:当并发数量较大时,会出现数据冲突,求改进方案
using System;
using System.Collections;
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;
using System.Net.Sockets;
using System.Collections.Specialized;
using System.Threading;

namespace SocketServer
{
    public partial class frmMain : Form
    {
        static int count = 0;
        static int recvCount = 0;

        public frmMain()
        {
            InitializeComponent();
        }

        private delegate void ShowMsgHandler(string msg);

        IList<Socket> clientList = new List<Socket>();
        Dictionary<Socket, System.Threading.Timer> clientArray = new Dictionary<Socket, System.Threading.Timer>();

        private void ShowMsg(string msg)
        {
            if (!txtContent.InvokeRequired)
            {
                txtContent.Text = msg + Environment.NewLine + txtContent.Text;
            }
            else
            {
                ShowMsgHandler handler = new ShowMsgHandler(ShowMsg);
                BeginInvoke(handler, new object[] { msg });
            }

        }

        private void btnStartServer_Click(object sender, EventArgs e)
        {
            IPAddress[] localIPs;
            localIPs = Dns.GetHostAddresses(Dns.GetHostName());
            StringCollection IpCollection = new StringCollection();
            foreach (IPAddress ip in localIPs)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork) //如果为IPv4
   &nb