我想现在是我问别人的时候了。是否可以使用 C# 和来自 HTML5 代码的服务器请求创建 websocket 服务器?
我目前正在为 websocket 使用系统包。我有一个通过互联网下载的代码,这里是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebSocketChatServer
{
using WebSocketServer;
class ChatServer
{
WebSocketServer wss;
List<User> Users = new List<User>();
string unknownName = "john doe";
public ChatServer()
{
// wss = new WebSocketServer(8181, "http://localhost:8080", "ws://localhost:8181/chat");
wss = new WebSocketServer(8080, "http://localhost:8080", "ws://localhost:8080/dotnet/Chats");
wss.Logger = Console.Out;
wss.LogLevel = ServerLogLevel.Subtle;
wss.ClientConnected += new ClientConnectedEventHandler(OnClientConnected);
wss.Start();
KeepAlive();
}
private void KeepAlive()
{
string r = Console.ReadLine();
while (r != "quit")
{
if(r == "users")
{
Console.WriteLine(Users.Count);
}
r = Console.ReadLine();
}
}
void OnClientConnected(WebSocketConnection sender, EventArgs e)
{
Console.WriteLine("test");
Users.Add(new User() { Connection = sender });
sender.Disconnected += new WebSocketDisconnectedEventHandler(OnClientDisconnected);
sender.DataReceived += new DataReceivedEventHandler(OnClientMessage);
}
void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e)
{
Console.WriteLine(sender);
User user = Users.Single(a => a.Connection == sender);
if (e.Data.Contains("/nick"))
{
string[] tmpArray = e.Data.Split(new char[] { ' ' });
if (tmpArray.Length > 1)
{
string myNewName = tmpArray[1];
while (Users.Where(a => a.Name == myNewName).Count() != 0)
{
myNewName += "_";
}
if (user.Name != null)
wss.SendToAll("server: '" + user.Name + "' changed name to '" + myNewName + "'");
else
sender.Send("you are now know as '" + myNewName + "'");
user.Name = myNewName;
}
}
else
{
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAllExceptOne(name + ": " + e.Data, sender);
sender.Send("me: " + e.Data);
}
}
void OnClientDisconnected(WebSocketConnection sender, EventArgs e)
{
try
{
User user = Users.Single(a => a.Connection == sender);
string name = (user.Name == null) ? unknownName : user.Name;
wss.SendToAll("server: "+name + " disconnected");
Users.Remove(user);
}
catch (Exception exc)
{
Console.WriteLine("ehm...");
}
}
}
}
我有这个客户端代码:
<!HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
var socket = new WebSocket("ws://localhost:8080");
socket.onopen = function(){
alert("Socket has been opened!");
}
});
</script>
</head>
</HTML>
当我运行我的 C# 控制台应用程序并加载客户端页面时,该应用程序告诉我有人连接到它正在侦听的端口。但是在我的客户端,当我查看萤火虫的控制台时,它给了我初学者的经典错误:
Firefox can't establish a connection to the server at ws://localhost:8080/
我想要实现的是首先建立一个成功的 websocket 连接并将值从我的服务器推送到我的客户端。
我考虑过 Alchemy,但我拥有的版本是 Visual Studio express 2010,免费版本,它说“此版本的应用程序不支持解决方案文件夹”。
任何帮助将不胜感激。