¿Hay un cliente WebSocket implementado para .NET? [cerrado]
Pregunta
Me gustaría utilizar WebSockets en mis Windows Forms o WPF-aplicación. ¿Hay un NET-control que está apoyando WebSockets aplicado todavía? O hay cualquier proyecto de código abierto comenzaron al respecto?
Una solución de código abierto para un cliente Java que sea compatible WebSockets podría también ayudar a mí.
Solución
Ahora, SuperWebSocket también incluye una aplicación cliente WebSocket SuperWebSocket página principal de
Otras implementaciones de cliente .NET incluyen:
Otros consejos
Aquí está un primer pase rápido a portar ese código Java a C #. No es compatible con el modo SSL y sólo se ha probado muy a la ligera, pero es un comienzo.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class WebSocket
{
private Uri mUrl;
private TcpClient mClient;
private NetworkStream mStream;
private bool mHandshakeComplete;
private Dictionary<string, string> mHeaders;
public WebSocket(Uri url)
{
mUrl = url;
string protocol = mUrl.Scheme;
if (!protocol.Equals("ws") && !protocol.Equals("wss"))
throw new ArgumentException("Unsupported protocol: " + protocol);
}
public void SetHeaders(Dictionary<string, string> headers)
{
mHeaders = headers;
}
public void Connect()
{
string host = mUrl.DnsSafeHost;
string path = mUrl.PathAndQuery;
string origin = "http://" + host;
mClient = CreateSocket(mUrl);
mStream = mClient.GetStream();
int port = ((IPEndPoint)mClient.Client.RemoteEndPoint).Port;
if (port != 80)
host = host + ":" + port;
StringBuilder extraHeaders = new StringBuilder();
if (mHeaders != null)
{
foreach (KeyValuePair<string, string> header in mHeaders)
extraHeaders.Append(header.Key + ": " + header.Value + "\r\n");
}
string request = "GET " + path + " HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: " + host + "\r\n" +
"Origin: " + origin + "\r\n" +
extraHeaders.ToString() + "\r\n";
byte[] sendBuffer = Encoding.UTF8.GetBytes(request);
mStream.Write(sendBuffer, 0, sendBuffer.Length);
StreamReader reader = new StreamReader(mStream);
{
string header = reader.ReadLine();
if (!header.Equals("HTTP/1.1 101 Web Socket Protocol Handshake"))
throw new IOException("Invalid handshake response");
header = reader.ReadLine();
if (!header.Equals("Upgrade: WebSocket"))
throw new IOException("Invalid handshake response");
header = reader.ReadLine();
if (!header.Equals("Connection: Upgrade"))
throw new IOException("Invalid handshake response");
}
mHandshakeComplete = true;
}
public void Send(string str)
{
if (!mHandshakeComplete)
throw new InvalidOperationException("Handshake not complete");
byte[] sendBuffer = Encoding.UTF8.GetBytes(str);
mStream.WriteByte(0x00);
mStream.Write(sendBuffer, 0, sendBuffer.Length);
mStream.WriteByte(0xff);
mStream.Flush();
}
public string Recv()
{
if (!mHandshakeComplete)
throw new InvalidOperationException("Handshake not complete");
StringBuilder recvBuffer = new StringBuilder();
BinaryReader reader = new BinaryReader(mStream);
byte b = reader.ReadByte();
if ((b & 0x80) == 0x80)
{
// Skip data frame
int len = 0;
do
{
b = (byte)(reader.ReadByte() & 0x7f);
len += b * 128;
} while ((b & 0x80) != 0x80);
for (int i = 0; i < len; i++)
reader.ReadByte();
}
while (true)
{
b = reader.ReadByte();
if (b == 0xff)
break;
recvBuffer.Append(b);
}
return recvBuffer.ToString();
}
public void Close()
{
mStream.Dispose();
mClient.Close();
mStream = null;
mClient = null;
}
private static TcpClient CreateSocket(Uri url)
{
string scheme = url.Scheme;
string host = url.DnsSafeHost;
int port = url.Port;
if (port <= 0)
{
if (scheme.Equals("wss"))
port = 443;
else if (scheme.Equals("ws"))
port = 80;
else
throw new ArgumentException("Unsupported scheme");
}
if (scheme.Equals("wss"))
throw new NotImplementedException("SSL support not implemented yet");
else
return new TcpClient(host, port);
}
}
Soporte para WebSockets es viene en .NET 4.5 . Que los enlaces también contiene un ejemplo usando el sistema de . Net.WebSockets.WebSocket clase.
Kaazing.com proporcionan una biblioteca cliente .NET que puede acceder websockets. Tienen tutoriales en línea en Lista de comprobación: crear clientes de Microsoft .NET JMS y Lista de comprobación: crear clientes de Microsoft .NET AMQP
Hay una de Java WebSocket proyecto de cliente en github.
Hay una aplicación cliente: http://websocket4net.codeplex.com/
otra opción:. XSockets.Net , tiene implementar servidor y el cliente
puede instalar el servidor por:
PM> Install-Package XSockets
o instalar el cliente de:
PM> Install-Package XSockets.Client
versión actual es: 3.0.4
Esta es la lista de los paquetes soportados NuGet WebSocket .net
Yo prefiero siguientes clientes
es un protocolo bastante simple. hay una aplicación java aquí que no debería ser demasiado difícil de traducir en C #. si me da la vuelta para hacerlo, voy a publicar aquí ...
Recientemente los puentes y los laboratorios de Centro de Interoperabilidad publicó un prototipo de aplicación (en código administrado) de dos borradores de la especificación del protocolo WebSockets:
proyecto-hixie-thewebsocketprotocol-75 y proyecto-hixie-thewebsocketprotocol-76
El prototipo se puede encontrar en HTML5 Labs. Me puse en esta entrada del blog toda la información he encontrado (hasta ahora) y fragmentos de código acerca de cómo se puede hacer esto utilizando WCF.
Si desea algo un poco más ligero, echa un vistazo a un servidor de C # que un amigo y yo liberarse: https://github.com/Olivine-Labs/Alchemy-Websockets
Soporta websockets vainilla, así como websockets flash. Fue construido para nuestro juego en línea con un enfoque en la escalabilidad y la eficiencia.
También hay Alquimia. http://olivinelabs.com/Alchemy-Websockets/ que es bastante fresco.