如何使用 ASP.NET 4.0 (C#) 创建一个简单的 HTML5 Websockets 应用程序。我的问题是关于创建 Websockets。以下是尝试过的代码...
try
{
var listener = new TcpListener(IPAddress.Loopback, 9988);
listener.Start();
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: http://localhost:9988");
writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
writer.WriteLine("");
}
listener.Stop();
}
catch (Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "", ex.Message);
}
HTML代码如下...!
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var status = '';
function conStatus(state) {
return (state == 0) ? 'Connecting..!' : (state == 1) ? 'Opened..!' : (state == 2) ? 'Closing..!' : 'Closed..!';
}
function WebSocketTest() {
if ("WebSocket" in window) {
try {
debugger;
var connection = new WebSocket('ws://localhost:9988');
status += '<br/>Socket Status: ' + conStatus(connection.readyState);
connection.onopen = function () {
status += 'Socket Opened..!';
};
connection.onmessage = function () {
status += 'Socket received a message..!';
};
connection.onclose = function () {
status += 'Socket Closed..!';
};
connection.send('Hello World..!');
}
catch (exception) {
status += '<br/>EXCEPTION: ' + exception;
}
}
else {
status += "Your Browser does not support WebSockets...!"
}
document.write(status);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
<div id="status">
</div>
</form>
</body>
</html>
如果我运行这个文件,页面会继续加载..我看不到任何结果..!请给我一个解决方案....提前谢谢....