开发者

select() function in C#

im new to C# and any help/feedback would be appreciated. im trying to develop a a client-server program in c#, however i do have different clients sending information to the server side. Is there any function similar to the c language select() such that can help to get all the information from every client side in C#?

here is my server side code:

// Create the listening socket...
m_mainSocket = new Socket(AddressFamily.InterNetwork, 
                          SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 9051);

// Bind to local IP Address...
m_mainSocket.Bind(ipLocal);

// Start listening...
m_mainSocket.Listen(10);
Socket clientSock = m_mainSocket.Accept();
byte[] clientData = new byte[1024];
int receivedBytesLen = clientSock.Receive(clientData);
string clientDataInString = 
           Encoding.ASCII.GetString(clientData, 0, receivedBytesLen);
string clientStr = "Client Data Received: " + clientDataInString;
byte[] sendData = new byte[1024];
sendData = 开发者_运维技巧Encoding.ASCII.GetBytes(clientStr);
clientSock.Send(sendData);
clientSock.Close();


There are higher level constructs, but if you want to get pretty low level, you are probably looking for Socket.Accept:

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept.aspx


You want to accept connections from more than one client, so you have to call the blocking Accept method again after acception a connection:

while (true)
{            
    var clientSocket = s.Accept();
    beginReceive(clientSocket);
}

After accepting you might want to start receiving data in an async manner:

private static void beginReceive(Socket clientSocket)
{
    byte[] buffer = new byte[1000];
    clientSocket.BeginReceive(
           buffer, 0, 1000, SocketFlags.None, OnReceiveData, clientSocket);
}

And finally here is the callback method which is called by the framework on another thread when data arrives. You have to finish the async call with EndReceive:

private static void OnReceiveData(IAsyncResult ar)
{
    int bytesReceived = ((Socket) ar.AsyncState).EndReceive(ar);
    // process data...
}

Of cause you have to store your buffer somewhere else and maintain one receive buffer per client. Maybe you should write an own class for managing a connected client.


Here is a code project with some nice diagrams and examples. The underlying "select" is handled by the .NET framework so you have to think / work at a higher level.

At a high level you socket.accept create a thread to process the connection.

http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.accept.aspx http://www.codeproject.com/KB/IP/dotnettcp.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜