C# ClientWebSocket implementation [closed]
up vote
-1
down vote
favorite
I'm working on implementing websockets in my current project in C#. Could anyone please give me some pointers/suggestions for what could be improved? Specifically, I'm most unsure about how to actually use this class in my main code. I can't figure out when/how I would use UsableWebsocket.Send()
though!
public class UsableWebsocket
{
public int BufferSize = 512;
public bool IsVerbose = false;
public event Action<string> OnReceiveMessage = delegate { };
private ClientWebSocket socket;
private readonly UTF8Encoding encoder = new UTF8Encoding();
private readonly object consoleLock = new object();
public UsableWebsocket(int bufferSize = 512, bool isVerbose = false)
{
BufferSize = bufferSize;
IsVerbose = isVerbose;
}
public async Task ConnectTo(string uri)
{
socket = null;
try
{
socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket connected.");
Console.ResetColor();
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
finally
{
if (socket != null)
socket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
public async Task Send(string message)
{
byte buffer = encoder.GetBytes(message);
await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}
public async Task Listen()
{
while (socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[BufferSize]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var mess = reader.ReadToEnd();
OnReceiveMessage(mess);
if (IsVerbose)
{
LogStatus(mess);
}
}
}
}
}
}
private void LogStatus(string message)
{
lock (consoleLock)
{
DateTime now = DateTime.UtcNow;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[{now.Hour:00}:{now.Minute:00}:{now.Second:00}] {message}");
Console.ResetColor();
}
}
}
And the usage would be something like:
static void Main(string args)
{
new Thread( async () =>
{
Thread.CurrentThread.IsBackground = true;
socket = new UsableWebsocket();
socket.OnReceiveMessage += BitmexApi.ParseMessage;
await socket.ConnectTo(wsurl);
socket.Listen();
}).Start();
// do other things as necessary
}
c# .net websocket
closed as off-topic by t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher Dec 11 at 12:53
This question appears to be off-topic. The users who voted to close gave this specific reason:
- "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher
If this question can be reworded to fit the rules in the help center, please edit the question.
add a comment |
up vote
-1
down vote
favorite
I'm working on implementing websockets in my current project in C#. Could anyone please give me some pointers/suggestions for what could be improved? Specifically, I'm most unsure about how to actually use this class in my main code. I can't figure out when/how I would use UsableWebsocket.Send()
though!
public class UsableWebsocket
{
public int BufferSize = 512;
public bool IsVerbose = false;
public event Action<string> OnReceiveMessage = delegate { };
private ClientWebSocket socket;
private readonly UTF8Encoding encoder = new UTF8Encoding();
private readonly object consoleLock = new object();
public UsableWebsocket(int bufferSize = 512, bool isVerbose = false)
{
BufferSize = bufferSize;
IsVerbose = isVerbose;
}
public async Task ConnectTo(string uri)
{
socket = null;
try
{
socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket connected.");
Console.ResetColor();
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
finally
{
if (socket != null)
socket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
public async Task Send(string message)
{
byte buffer = encoder.GetBytes(message);
await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}
public async Task Listen()
{
while (socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[BufferSize]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var mess = reader.ReadToEnd();
OnReceiveMessage(mess);
if (IsVerbose)
{
LogStatus(mess);
}
}
}
}
}
}
private void LogStatus(string message)
{
lock (consoleLock)
{
DateTime now = DateTime.UtcNow;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[{now.Hour:00}:{now.Minute:00}:{now.Second:00}] {message}");
Console.ResetColor();
}
}
}
And the usage would be something like:
static void Main(string args)
{
new Thread( async () =>
{
Thread.CurrentThread.IsBackground = true;
socket = new UsableWebsocket();
socket.OnReceiveMessage += BitmexApi.ParseMessage;
await socket.ConnectTo(wsurl);
socket.Listen();
}).Start();
// do other things as necessary
}
c# .net websocket
closed as off-topic by t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher Dec 11 at 12:53
This question appears to be off-topic. The users who voted to close gave this specific reason:
- "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher
If this question can be reworded to fit the rules in the help center, please edit the question.
1
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
1
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54
add a comment |
up vote
-1
down vote
favorite
up vote
-1
down vote
favorite
I'm working on implementing websockets in my current project in C#. Could anyone please give me some pointers/suggestions for what could be improved? Specifically, I'm most unsure about how to actually use this class in my main code. I can't figure out when/how I would use UsableWebsocket.Send()
though!
public class UsableWebsocket
{
public int BufferSize = 512;
public bool IsVerbose = false;
public event Action<string> OnReceiveMessage = delegate { };
private ClientWebSocket socket;
private readonly UTF8Encoding encoder = new UTF8Encoding();
private readonly object consoleLock = new object();
public UsableWebsocket(int bufferSize = 512, bool isVerbose = false)
{
BufferSize = bufferSize;
IsVerbose = isVerbose;
}
public async Task ConnectTo(string uri)
{
socket = null;
try
{
socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket connected.");
Console.ResetColor();
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
finally
{
if (socket != null)
socket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
public async Task Send(string message)
{
byte buffer = encoder.GetBytes(message);
await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}
public async Task Listen()
{
while (socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[BufferSize]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var mess = reader.ReadToEnd();
OnReceiveMessage(mess);
if (IsVerbose)
{
LogStatus(mess);
}
}
}
}
}
}
private void LogStatus(string message)
{
lock (consoleLock)
{
DateTime now = DateTime.UtcNow;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[{now.Hour:00}:{now.Minute:00}:{now.Second:00}] {message}");
Console.ResetColor();
}
}
}
And the usage would be something like:
static void Main(string args)
{
new Thread( async () =>
{
Thread.CurrentThread.IsBackground = true;
socket = new UsableWebsocket();
socket.OnReceiveMessage += BitmexApi.ParseMessage;
await socket.ConnectTo(wsurl);
socket.Listen();
}).Start();
// do other things as necessary
}
c# .net websocket
I'm working on implementing websockets in my current project in C#. Could anyone please give me some pointers/suggestions for what could be improved? Specifically, I'm most unsure about how to actually use this class in my main code. I can't figure out when/how I would use UsableWebsocket.Send()
though!
public class UsableWebsocket
{
public int BufferSize = 512;
public bool IsVerbose = false;
public event Action<string> OnReceiveMessage = delegate { };
private ClientWebSocket socket;
private readonly UTF8Encoding encoder = new UTF8Encoding();
private readonly object consoleLock = new object();
public UsableWebsocket(int bufferSize = 512, bool isVerbose = false)
{
BufferSize = bufferSize;
IsVerbose = isVerbose;
}
public async Task ConnectTo(string uri)
{
socket = null;
try
{
socket = new ClientWebSocket();
await socket.ConnectAsync(new Uri(uri), CancellationToken.None);
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket connected.");
Console.ResetColor();
}
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
finally
{
if (socket != null)
socket.Dispose();
Console.WriteLine();
lock (consoleLock)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("WebSocket closed.");
Console.ResetColor();
}
}
}
public async Task Send(string message)
{
byte buffer = encoder.GetBytes(message);
await socket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
}
public async Task Listen()
{
while (socket.State == WebSocketState.Open)
{
var buffer = new ArraySegment<byte>(new byte[BufferSize]);
WebSocketReceiveResult result = null;
using (var ms = new MemoryStream())
{
do
{
result = await socket.ReceiveAsync(buffer, CancellationToken.None);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType == WebSocketMessageType.Text)
{
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
var mess = reader.ReadToEnd();
OnReceiveMessage(mess);
if (IsVerbose)
{
LogStatus(mess);
}
}
}
}
}
}
private void LogStatus(string message)
{
lock (consoleLock)
{
DateTime now = DateTime.UtcNow;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"[{now.Hour:00}:{now.Minute:00}:{now.Second:00}] {message}");
Console.ResetColor();
}
}
}
And the usage would be something like:
static void Main(string args)
{
new Thread( async () =>
{
Thread.CurrentThread.IsBackground = true;
socket = new UsableWebsocket();
socket.OnReceiveMessage += BitmexApi.ParseMessage;
await socket.ConnectTo(wsurl);
socket.Listen();
}).Start();
// do other things as necessary
}
c# .net websocket
c# .net websocket
edited Dec 11 at 3:22
Jamal♦
30.2k11115226
30.2k11115226
asked Dec 10 at 20:25
theagemaway
1
1
closed as off-topic by t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher Dec 11 at 12:53
This question appears to be off-topic. The users who voted to close gave this specific reason:
- "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher
If this question can be reworded to fit the rules in the help center, please edit the question.
closed as off-topic by t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher Dec 11 at 12:53
This question appears to be off-topic. The users who voted to close gave this specific reason:
- "Code not implemented or not working as intended: Code Review is a community where programmers peer-review your working code to address issues such as security, maintainability, performance, and scalability. We require that the code be working correctly, to the best of the author's knowledge, before proceeding with a review." – t3chb0t, Nic Hartley, Zeta, BCdotWEB, Heslacher
If this question can be reworded to fit the rules in the help center, please edit the question.
1
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
1
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54
add a comment |
1
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
1
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54
1
1
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
1
1
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54
add a comment |
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
1
To be clear, does your code work as expected and do everything you want? That is, are you looking for help to get the code working at all, or are you trying to get it to work better?
– Nic Hartley
Dec 11 at 1:38
Sorry for the lack of clarity. It currently does not work. As far as I can tell, each individual function in the UsableWebsockets class perform as intended, however, I can't figure out how to use them as a cohesive unit inside my Main function.
– theagemaway
Dec 11 at 2:13
1
It's off-topic for this site, then. Code Review is to review working code, to say what could be improved style-wise and performance-wise. You'll have better luck on Stack Overflow.
– Nic Hartley
Dec 11 at 8:54