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

多线程模拟客户端问题
改写testclient,用多线程模拟多个客户端。
申请10000个线程和10000个连接,每个线程对应唯一的一个连接。
1.先测出一个客户端1秒内向服务器发送消息,间隔多长时间可将消息数量控制在10~15的范围内。
经过简单的修改Thread.Sleep的参数,得出当参数值为60ms时,消息数量始终为16或17,不符合标准;当参数值为70ms时,消息数量始终为14或15,符合标准;当参数值为80ms时,消息数量始终为12或13,符合标准;当参数值为90ms时,消息数量始终为11或12,符合标准;当参数值为100ms时,消息数量始终为9或10,不符合标准;
为减轻服务器载重,并且保证性能,下面测试时使用的参数均设为90.
2.利用for循环初始化功能线程(建立连接并发送消息),预设每隔1s初始化一个线程,检测发送消息是否存在异常。
测试结果显示,当调用第6个线程时出现异常,异常代码段为client[Program.count].SendTo(BufferFormatV2.FormatFCA(temp));
说明第6个线程发送数据过程有问题,很有可能服务器只能接收5台客户端同时每1S发送11~12条消息。
3.重复多次进行步骤2.发现至少有4个线程同时存在时,才会出现2中问题。但是运行多个客户端单线程测试,就不会出现这种异常。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BasicSocket.Client;
using System.IO;
using BasicSocket.Data;
using System.Globalization;
using System.Threading;
using System.Net;

namespace testclient
{

    public class Connect
    {
        /// <summary>
        /// 建立一个SOCKET客户端
        /// </summary>
        public static SocketClient[] client = new SocketClient[10000];
        // This method will be called when the thread is started.
        public void DoWork()
        {
            client[Program.count] = new SocketClient();
            //client.DataOn += new DataOn(client_DataOn); //数据包进入事件

            //client.Disconnection += new ExceptionDisconnection(client_Disconnection); //数据包断开事件
            string hostip = "192.168.1.17";

            string localip = Program.ipAddress + ":" + Convert.ToString(Program.count);
            try
            {
                //if (client.ConnectionTo(hostip, 9982)) //使用同步连接到服务器,一步就用Begin开头的那个
                if (client[Program.count].ConnectionTo(hostip, 9982)) //使用同步连接到服务器,一步就用Begin开头的那个
                {
                    while (true)
                    {
                        //string localip = Console.ReadLine();
                        Thread.Sleep(90);      //防止调用频繁访问冲突
   &n