Websocket sharp , reading server variable from onmessage - c#

Hello I am new on web sockets so was wondering what am I doing wrong here, I have a server and client
code looks something like this
public class SampleSocketService: WebSocketBehavior
{
private int globalvar = 1;
protected override void OnMessage(MessageEventArgs e)
{
if(...somecondition)
{
while(...loopcondition)
globalvar++;
}
if(...anothercondition)
{
this.Send(globalvar);
}
}
}
problem is when I am sending to client the globalvar it is always = 1
Any ideas?

Related

Remove RoleInstance from data sent to Azure Application Insights from WPF

I'm trying to add Application Insights to a WPF app using this documentation: https://learn.microsoft.com/en-us/azure/azure-monitor/app/windows-desktop. The basic integration is working. I am now trying to remove the RoleInstance property from the submitted data, as described in the documentation, as this contains the user's computer name (personally identifiable information). Here's my code, based on the documentation above:
Telemetry.cs
public static class Telemetry
{
public static TelemetryClient Client;
public static void Close()
{
if (Client != null)
{
Client.Flush();
System.Threading.Thread.Sleep(1000);
}
}
public static void Initialize()
{
TelemetryConfiguration.Active.InstrumentationKey = "xxxxxxxx";
TelemetryConfiguration.Active.TelemetryInitializers.Add(new MyTelemetryInitializer());
Client = new TelemetryClient(TelemetryConfiguration.Active);
Client.Context.Session.Id = Guid.NewGuid().ToString();
Client.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
}
private class MyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (string.IsNullOrEmpty(telemetry.Context.Cloud.RoleName))
{
telemetry.Context.Cloud.RoleInstance = null;
}
}
}
}
App.xaml.cs
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
Telemetry.Close();
base.OnExit(e);
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Telemetry.Initialize();
}
}
When I call Telemetry.Client.TrackEvent(), Telemetry.Initialize() runs, and RoleInstance is null from the start. But, the data sent to AI contains my computer name as the RoleInstance. Not sure how to debug further.
Note: the documentation describes integration into WinForms, and I'm in WPF, so I've guessed at using App.OnStartup instead of Main.
I just found something interesting, if you set a dummy value for RoleInstance, it really takes effect. Maybe the null/empty value will be checked and replaced by the real RoleInstance in the backend. As a workaround, you can just specify a dummy value instead of null/empty value.
Here is my test result with a dummy value:
in azure portal:

Weird behavior with socketIO and .NET clients

I'm using socketIO on node and hook it up with the front-end, they work fine
Now I want to push things further
I want my .net clients (UWP) communicate with the socketIO
But there is something really weird happening
At first I tested and it run just fine, the second time I run the client
It started to send twice or more messages when I only send one. And I realize that if I open the .net client first and the server later this won't happen, but when I shut my clients down (while the server still running) this bug started to happen.
public sealed partial class StuffDetail : Page
{
Socket socket = IO.Socket("ws://localhost:8888");
ObservableCollection<SocketMessage> InCommingData { get; set; } = new ObservableCollection<SocketMessage>();
public StuffDetail()
{
this.InitializeComponent();
DisconnectState();
SetSocket();
ChatWindow.ItemsSource = InCommingData;
}
private void DisconnectState()
{
ReceivedText.Text = "Not Connect";
}
private void SetSocket()
{
socket.Connect();
ReceivedText.Text = "Connect Completed";
socket.On("chat", async (data) =>
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var IncomeMess = JsonConvert.DeserializeObject<SocketMessage>(data.ToString());
InCommingData.Add(IncomeMess);
});
});
}
private void Send(object sender, RoutedEventArgs e)
{
var message = new SocketMessage()
{
message = MessTextBox.Text,
handle = "From Beta User"
};
socket.Emit("chat", JsonConvert.SerializeObject(message));
}
}

Converting Client String to Array on Server C#

I want to convert the string the server is receiving from the client to in an array. However when I use the String.Split method the result variable is showing null. Anyone know why that might be?
namespace ExampleLib.Server
{
public class Server
{
private class ConnectedClient
{
public int ID { get; }
private TcpClient _client;
private StreamReader _streamReader;
public delegate void NetDataEventHandler(object sender, NetDataEventArgs e);
public event NetDataEventHandler NetData;
public virtual void OnNetData(NetDataEventArgs e)
{
NetData?.Invoke(this, e);
}
public class NetDataEventArgs
{
public NetDataEventArgs(int id, string message)
{
ID = id;
Message = message;
}
public string Message { get; }
public int ID { get; }
}
public ConnectedClient(int id, TcpClient client)
{
ID = id;
_client = client;
}
private void ClientReceiveData(object sender, ConnectedClient.NetDataEventArgs e)
{
if (string.IsNullOrEmpty(e.Message) == false)
{
Trace.WriteLine($" Client {e.ID}: {e.Message}");
var result = e.Message.Split(',');
}
}
You have stopped at the break-point.
You should proceed one more step, in order for that line to be executed.
Currently, you're at a step similar to this.
If you proceed one more step using F10 (or 'Step Over' button) , it will execute that line and assign the value of addition to c in this example.

Console C# check for internet availability and wait until it is not available

I have been searching for the code which will help me if the internet connection breaks in between.
I am having a console app which takes data from database and sends mail in bulk. Now while sending mails if internet connection fails than I want to wait until internet is available.
I got good ans here
public static void ConnectToPUServer()
{
var client = new WebClient();
while (i < 500 && networkIsAvailable)
{
string html = client.DownloadString(URI);
//some data processing
Console.WriteLine(i);
i++;
URI = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/" + i + "/";
}
Console.WriteLine("Complete.");
writer.Close();
}
static void NetworkChange_NetworkAvailabilityChanged(object sender,NetworkAvailabilityEventArgs e)
{
networkIsAvailable = e.IsAvailable;
if (!networkIsAvailable)
{
Console.WriteLine("Internet connection not available! We resume as soon as network is available...");
}
else
{
ConnectToPUServer();
}
}
This is not exactly what I want. But I want to apply something similar to this. Can anybody help me how to implement this? I mean what is ConnectToPUServer and when NetworkChange_NetworkAvailabilityChanged will be executed and what namespace to be used?
you can use the below mentioned code for it you have to use
using System.Net.NetworkInformation;
public partial class MainWindow : Window
{
public bool IsAvailable { get; set; }
public MainWindow()
{
InitializeComponent();
NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
}
void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
IsAvailable = e.IsAvailable;
}
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
if (IsAvailable)
{
WebBrowser1.Navigate(TextBox1.Text);
}
else
{
MessageBox.Show("Your Popup Message");
}
}
}

C# Web Traffic Listener

I am trying to write a simple c# console application which shows the accessed websites (sort of proxy server) . I understood that the right approach would be using .Net Sockets and TCP Listeners. However, I tried some code samples and I can get working none of them.
Any suggestions would be great!
You can use FiddlerCore
public class HttpProxy : IDisposable
{
public HttpProxy()
{
Fiddler.FiddlerApplication.BeforeRequest += FiddlerApplication_BeforeRequest;
Fiddler.FiddlerApplication.Startup(8888, true, true);
}
void FiddlerApplication_BeforeRequest(Fiddler.Session oSession)
{
Console.WriteLine(String.Format("REQ: {0}", oSession.url));
}
public void Dispose()
{
Fiddler.FiddlerApplication.Shutdown();
}
}
static void Main(string[] Args)
{
var p = new HttpProxy();
Console.ReadLine();
p.Dispose();
}

Categories