본문 바로가기

.NET/ASP.NET

.Net 4.5 와 IIS8에서 Websocket을 지원합니다.

아.. 드디어
 MS에서 웹소켓을 지원하네요 지금은

IIS8과 .Net4.5가 베타 버전이지만

웹소켓을 확실히 지원하네요 모두 기뻐하시길....

사용법은 간단하고 심플하며 아래와 같습니다.

public async Task MyWebSocket(AspNetWebSocketContext context)
 
{
   
WebSocket socket = context.WebSocket;
   
while (true)
   
{
       
ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
 
       
// Asynchronously wait for a message to arrive from a client
       
WebSocketReceiveResult result =
            await socket
.ReceiveAsync(buffer, CancellationToken.None);
 
       
// If the socket is still open, echo the message back to the client
       
if (socket.State == WebSocketState.Open)
       
{
           
string userMessage = Encoding.UTF8.GetString(buffer.Array, 0,
                result
.Count);
            userMessage
= "You sent: " + userMessage + " at " +
               
DateTime.Now.ToLongTimeString();
            buffer
= new ArraySegment<byte>(Encoding.UTF8.GetBytes(userMessage));
 
           
// Asynchronously send a message to the client
            await socket
.SendAsync(buffer, WebSocketMessageType.Text,
               
true, CancellationToken.None);
       
}
       
else { break; }
   
}
}
// Receive a string message from the server.
 socket
.onmessage = function(msg)
 
{
    document
.getElementById("serverData").innerHTML = msg.data;
};
// Send a string message from the browser.
 socket.send(document.getElementById("msgText"));