2024年6月11日发(作者:)

C#下用select方法实现socket服务端

select是一种比较古老但一直被证明性能很好的socket

模式,它可以让你以消息驱动的模式书写socket程序。网上

C++的例子很多,但C#的例子极少。上代码:[csharp] view

plain copynamespace Server { class Program

{ // Thread signal. public static

ManualResetEvent allDone = new

ManualResetEvent(false); private static Socket

handler = null; private static ArrayList g_CliSocketArr

= new ArrayList(); private static Object thisLock =

new Object(); public Program() { }

public static void StartListening() { // Data buffer

for incoming data. byte[] bytes = new Byte[1024];

IPAddress ipAddress =

("0.0.0.0");//0.0.0.0表示监听本机的所有

IP IPEndPoint localEndPoint = new

IPEndPoint(ipAddress, 11000); // Create a

TCP/IP socket. Socket listener = new

Socket(etwork,

, );

// Bind the socket to the local endpoint and listen for

incoming connections. try

{ (localEndPoint);

(100); // Start an

asynchronous socket to listen for connections.

ine("Waiting for ");

Thread worker = new Thread(new

ThreadStart(WorkerThread));//创建一个线程用于处理请求

(); while (true)

{ Socket sClient = ();

ine("There is a new connection.");

g_(sClient);

} } catch (Exception e)

{ ine(ng());

} ine("nPress ENTER to

"); (); }

public static void WorkerThread()

{ Socket socket1 = null;

ArrayList readList = new ArrayList(); //

(socket0); while (true)

{ lock (thisLock)

{ ();

for (int i = 0; i < g_; i++)

{ (g_CliSocketArr

[i]); } }

if ( <= 0)

{ (100);

continue; } try

{ (readList, null, null,

500); for (int i = 0; i <

; i++)

{ socket1 = (Socket)readList[i];

ine("There is a new message from client.");

byte[] buffer = new byte[1024];

int recLen = e(buffer);

if(recLen > 0)

{ // recLen =

e(buffer); }

else {//如果返回0,表示

客户端已经断开连接,须将此socket关闭然后从连接池中清

ine("Rece 0 length.");

for (int ii = 0; ii < g_; ii++)

{ Socket s =

(Socket)g_CliSocketArr[ii];

if (s == socket1)

g_At(ii);

}

wn();

();

break; }

(buffer,recLen,

);

} } catch

(SocketException e)

{ ine("{0} Error

code: {1}.", e, ode);

for (int ii = 0; ii < g_; ii++)

{ Socket s =

(Socket)g_CliSocketArr[ii]; if

(s == socket1)

g_At(ii); }

wn();

(); } }

} static void

Main(string[] args)

{ StartListening(); } }

}