读书人

new N个线程有关问题

发布时间: 2013-09-26 10:32:35 作者: rapoo

new N个线程问题
我想模拟N个客户端向服务器发送消息,以便测试服务器的负载性能。
客户端:

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;

namespace testclient
{

public class Connect
{
/// <summary>
/// 建立一个SOCKET客户端
/// </summary>
public static SocketClient client = new SocketClient();

// This method will be called when the thread is started.
public void DoWork()
{
//client.DataOn += new DataOn(client_DataOn); //数据包进入事件

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

string localip = Convert.ToString(Program.count);

//if (client.ConnectionTo(hostip, 9982)) //使用同步连接到服务器,一步就用Begin开头的那个
if (client.ConnectionTo(hostip, 9982)) //使用同步连接到服务器,一步就用Begin开头的那个
{
while (true)
{
//string localip = Console.ReadLine();
Thread.Sleep(1000); //防止调用频繁访问冲突
SendDataClass.PPo temp = new SendDataClass.PPo();
temp.RealWeight = 14.5;


temp.ShaftType = 2;
temp.License = localip;
temp.Checker = "hongyu";
string uploadtime = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss", DateTimeFormatInfo.InvariantInfo);
temp.UploadTime = uploadtime;
client.SendTo(BufferFormatV2.FormatFCA(temp)); //用组合数据包模拟PPO对象 但GUID 是字符串类型;
//client.SendTo(BufferFormat.FormatFCA(temp));
}
client.Close();
}
else
{
Console.WriteLine(Convert.ToString(Program.count) + "无法连接服务器");
}

Console.ReadLine();

//while (!_shouldStop)
//{
// Console.WriteLine("worker thread: working...");
//}
//Console.WriteLine("worker thread: terminating gracefully.");
}

static void client_Disconnection(string message)
{
Console.WriteLine(message);


}

static void client_DataOn(byte[] Data)
{
throw new NotImplementedException();
}

//public void RequestStop()
//{
// _shouldStop = true;
//}
//// Volatile is used as hint to the compiler that this data
//// member will be accessed by multiple threads.
//private volatile bool _shouldStop;
}

class Program
{
public static int count = 0;

static void Main(string[] args)
{
Connect[] workerObject = new Connect[10000];
Thread[] workerThread = new Thread[10000];

//Console.WriteLine("main thread: Starting worker thread...");
//while (!workerThread.IsAlive);
for ( int i = 0; i < 10000; i++ )
{
workerObject[i] = new Connect();
workerThread[i] = new Thread(workerObject[i].DoWork);
count++;
workerThread[i].Start();
Thread.Sleep(1000);


//workerThread.Join();
Console.WriteLine("new thread." + Convert.ToString(count));

}
//Console.WriteLine("main thread: Worker thread has terminated.");

}

}
}


新建N个线程,每个线程模拟一个客户端,每个客户端循环向服务器发送消息。
但是输出结果只能建立一个连接,其他线程都不能连上服务器,我想问题应该出在客户端上,各位大侠帮忙看看怎么改! 测试 线程 服务器
[解决办法]
client是个公用的,每次都只存在一个连接,你要创建n个client

读书人网 >C#

热点推荐