我在JavaScript中使用WebSocket
类,并使用C#使用IIS套接字。当我运行我的应用程序并使用 ws:// localhost 套接字连接时,它已建立。当我使用 ws://127.0.0.1 或 ws:// myIpAddress 时,套接字连接是不明确的。
C#:
string xmlPath = System.Configuration.ConfigurationManager.AppSettings["CUSSiteDomainPhysicalPath"].ToString();
public override void OnOpen()
{
this.Send("Welcom from " + this.WebSocketContext.UserHostAddress);
// OnMessage("nirav patel");
}
public override void OnMessage(string message)
{
string msgBack = string.Format(
"You have sent {0} at {1}", message, DateTime.Now.ToLongTimeString());
this.Send(msgBack);
}
public void OnMessage1()
{
string msgBack = readxml();
Send(msgBack);
Task.Factory.StartNew(() =>
{
Thread.Sleep(700);
OnMessage1();
});
}
JavaScript的:
<script type="text/javascript">
var ws;
$().ready(function () {
$("#btnConnect").click(function () {
$("#spanStatus").text("connecting");
ws = new WebSocket("ws://localhost:2622/MSWSChatHandler.ashx");
ws.onopen = function () {
$("#spanStatus").text("connected");
};
ws.onmessage = function (evt) {
getLiveRate(evt.data);
$("#spanStatus").text(evt.data);
};
ws.onerror = function (evt) {
$("#spanStatus").text(evt.message);
};
ws.onclose = function () {
$("#spanStatus").text("disconnected");
};
});
$("#btnSend").click(function () {
if (ws.readyState == WebSocket.OPEN) {
ws.send($("#textInput").val());
}
else {
$("#spanStatus").text("Connection is closed");
}
});
$("#btnDisconnect").click(function () {
ws.nirav = function () {
debugger
};
});
});
</script>