我使用websocket服务器创建了一个.NET类套接字。当我的浏览器尝试连接到程序上的套接字时,我发现"accept socket"方法在浏览器连接后调用非常慢或几秒钟。我尝试创建许多连接,但套接字每秒都会接受一个websocket。我也尝试了炼金术websocket,结果就像我的代码一样。
当我在IIS8上使用Miscrosoft websocket后,我注意到速度相当不错。
我不是实验性的。
我的代码(快递)
class Connection
{
byte[] buffer = new byte[1024];
Socket socket;
bool IsAuthencation;
public Connection(Socket socket)
{
this.socket = socket;
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
void OnReceive(IAsyncResult result)
{
try
{
int count = socket.EndReceive(result);
if (count != 0)
{
if (!IsAuthencation)
{
byte[] tmp = new byte[count];
Array.Copy(buffer, 0, tmp, 0, count);
string Request = Encoding.UTF8.GetString(tmp);
if (Request.Contains("GET"))
{
if (!IsAuthencation)
{
int indexStart = Request.IndexOf("Sec-WebSocket-Key: ");
int indexEnd = Request.IndexOf("Sec-WebSocket-Version:");
string key = Request.Substring(indexStart + 19, indexEnd - indexStart - 21);
string magic = string.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
string base64 = "";
using (SHA1 sha1 = SHA1.Create())
{
byte[] bufferMagic = sha1.ComputeHash(Encoding.UTF8.GetBytes(magic));
base64 = Convert.ToBase64String(bufferMagic);
}
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + base64
+ Environment.NewLine
+ Environment.NewLine);
socket.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
IsAuthencation = true;
}
}
}
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
else
{
// disconnect
}
}
catch (Exception)
{
}
}
void OnSend(IAsyncResult result)
{
try
{
socket.EndSend(result);
}
catch (Exception)
{
}
}
}
class Program
{
static List<Connection> clients;
static Socket socket;
static void Main(string[] args)
{
clients = new List<Connection>();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 30000);
socket.Bind(endPoint);
socket.Listen(0);
socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
Console.ReadLine();
}
static void AcceptAsync(IAsyncResult result)
{
Console.WriteLine("a new connection");
Socket s = socket.EndAccept(result);
clients.Add(new Connection(s));
socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
}
}
您可以尝试命令javascript var socket=new WebSocket("ws://localhost:30000"),我在代码中没有看到问题。感谢
您必须接受套接字,并异步处理它,然后立即返回接受更多套接字。
更新
在看到您的代码之后,您似乎正在异步地接受连接。您是如何创建这些测试连接的?如果你创建了太多,你可能会让应用程序饱和。
我想我看到了问题所在,为什么要将套接字囤积设置为0?阅读SO.的答案
试着放一个更大的值:socket.Listen(100);