日期:2014-05-18 浏览次数:20831 次
foreach (IPAddress item in Dns.GetHostEntry("").AddressList)
{
if (System.Text.RegularExpressions.Regex.IsMatch(item.ToString(),
Constants.RegularHttp))
{
ipa = item;
break;
}
}//监听端口2020
TcpListener mylistenter = new TcpListener(ipa, Constants.IPPort);
//ThreadPool.SetMinThreads(10, 10);
//ThreadPool.SetMaxThreads(100, 100);
try
{
mylistenter.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
mylistenter.Start();
FileConfig.WritetFile(Constants.FileListenter + mylistenter.LocalEndpoint.ToString());
//int a, b;
//等待处理接入连接请求
while (true)
{
mySocket = mylistenter.AcceptSocket();
ThreadPool.QueueUserWorkItem(DoWork.ReceiveMethod, mySocket);
}
}
catch (Exception ex)
{
FileConfig.WritetFile(Constants.FileException + ex.ToString());
}
finally
{ }
private static void ReceiveMethod(object state) { Socket socket = (Socket)state; int length = 0; byte[] byteData = null;//new byte[1024]; string request = string.Empty; string DataHeader = string.Empty; string DataTrunk = string.Empty; bool Flag = true; while (true) { Thread.Sleep(100); length = socket.Available; if (socket.Connected && length > 16) { try { byteData = new byte[length]; //将从客户端流读取的数据保存到字符串request中 socket.Receive(byteData); request = System.Text.UTF8Encoding.UTF8.GetString(byteData); DataHeader = string.Empty; DataTrunk = string.Empty; ReceiveData(request, ref DataHeader, ref DataTrunk); FileConfig.WritetFile(string.Format(Constants.FileNewData, DataHeader, DataTrunk, request.Length, request)); } catch (Exception ex) { FileConfig.WritetFile(socket.RemoteEndPoint.ToString() + Constants.FileColseException + ex.ToString()); /*if (listSocket.Contains(socket)) { listSocket.Remove(socket); } socket.Shutdown(SocketShutdown.Both); socket.Close();*/ } finally { } } } }
------解决方案--------------------
我最近也在学习这个东西
------解决方案--------------------
多线程不熟,那就先用单线程来实现,后面再优化
//ThreadPool.SetMinThreads(10, 10);
//ThreadPool.SetMaxThreads(100, 100);
其实随意设置它们并不好,因为你不知道客户机器的硬件配置。线程池是托管的,你不用去关心最大数和最小数,不要同时去开启太多的线程,同时保证线程能正常退出就行了
------解决方案--------------------