我想现在是我问其他人的时候了。是否可以使用 C# 和来自 HTML5 代码的服务器请求创建 websocket 服务器?

我目前正在为 websocket 使用 System 包。我有一个通过互联网下载的代码,它是:

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# 控制台应用程序并加载客户端页面时,该应用程序告诉我有人连接到它正在监听的端口。但是在我的客户端,当我查看 firebug 的控制台时,它给了我初学者的经典错误:
Firefox can't establish a connection to the server at ws://localhost:8080/

我想要实现的是首先建立一个成功的 websocket 连接,并将值从我的服务器推送到我的客户端。

我考虑过 Alchemy,但我拥有的版本是 Visual Studio express 2010,免费版本,它说“此版本的应用程序不支持解决方案文件夹”。

任何帮助将不胜感激。

最佳答案

我已经为 JavaScript/HTML 5 游戏开发服务器大约 7 个月了,现在您是否研究过 Alchemy Websockets?它很容易使用。

例子:

using Alchemy;
using Alchemy.Classes;
namespace GameServer
{
    static class Program
    {
        public static readonly ConcurrentDictionary<ClientPeer, bool> OnlineUsers = new ConcurrentDictionary<ClientPeer, bool>();
        static void Main(string[] args)
        {
            var aServer = new WebSocketServer(4530, IPAddress.Any)
            {
                OnReceive = context => OnReceive(context),
                OnConnected = context => OnConnect(context),
                OnDisconnect = context => OnDisconnect(context),
                TimeOut = new TimeSpan(0, 10, 0),
                FlashAccessPolicyEnabled = true
            };
        }
        private static void OnConnect(UserContext context)
        {
            var client = new ClientPeer(context);
            OnlineUsers.TryAdd(client, false);
            //Do something with the new client
        }
    }
}

正如您所看到的,它非常易于使用,而且我发现他们的文档非常好(注意 ClientPeer 是我的自定义类,只是将其用作示例)。

关于C# 作为 HTML5 websocket 连接的 Websocket 服务器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15378912/

10-17 00:03