i am using below socket functions to receive data from socket server, when i disconnect my network connection , and reconnect again socket application stop receiving data. I also tried to add a timer which check the state of socket every 20 sec but its not working. Any advise?
private WebSocket client; //before form_load
private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host);
client.OnOpen += (ss, ee) =>
{
MessageBox.Show(string.Format("Connected to {0} successfully ", host));
};
client.OnError += (ss, ee) =>
{
MessageBox.Show(" Error: " + ee.Message);
};
client.OnMessage += (ss, ee) =>
{
MessageBox.Show("Message: " + ee.Message);
};
client.OnClose += (ss, ee) =>
{
MessageBox.Show(string.Format("Disconnected with {0}", host));
};
client.Connect();
}
private void timer1_Tick(object sender, EventArgs e)
{
if(client.ReadyState.ToString()=="Closed")
{
client.Close();
client = new WebSocket(host);
client.Connect();
}
}
You didn't mention the web socket library/package you used. Here is a simple working reconnect example using WebSocket4Net.
Because of AutoSendPing it closes the connection when something happens to the network and timer tries to reconnect if the socket is closed.
private WebSocket client;
private void Form1_Load(object sender, EventArgs e)
{
client = new WebSocket(host)
{
EnableAutoSendPing = true,
AutoSendPingInterval = 10,
};
client.Opened += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Connected");
};
client.Error += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Error {ee.Exception}");
};
client.MessageReceived += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine($"Message: {ee.Message}");
};
client.Closed += (ss, ee) =>
{
System.Diagnostics.Debug.WriteLine("Disconnected");
};
client.Open();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (client.State == WebSocketState.Closed)
{
client.Open();
System.Diagnostics.Debug.WriteLine("Trying to reconnect by timer");
}
}
Related
There are loads of questions about listening of devices on Serial Port using C#.
However I couldn't find something about my problem.
Connected two serial port device one transmitter and one receiver.
When i start one application exe and check two port for listen async, after a
while the reading stops for one of the com ports.
There is no problem when I start separate application for each port.
ScreenShoot
public Form1()
{
InitializeComponent();
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
foreach (var item in ports)
{
checkedListBox1.Items.Add(item);
}
}
private void btnListenPort_Click(object sender, EventArgs e)
{
doWork(checkedListBox1);
}
private async Task doWork(CheckedListBox cbl)
{
try
{
foreach (var itemChecked in cbl.CheckedItems)
{
string sPort = itemChecked.ToString();
await Task.Run(() =>
{
ListenAsync(sPort);
});
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: {0}", ex.Message);
}
}
private void ListenAsync(string strPort) {
var serialPort = new SerialPort(strPort, 9600, Parity.None, 8, StopBits.One);
serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);
serialPort.Open();
}
private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort spL = (SerialPort)sender;
string incomSting = spL.ReadLine();
setText(spL.PortName + " " + incomSting);
}
delegate void serialCalback(string val);
private void setText(string val)
{
if (this.richTextBox1.InvokeRequired)
{
serialCalback scb = new serialCalback(setText);
this.Invoke(scb, new object[] { val });
}
else
{
richTextBox1.Text += Environment.NewLine;
richTextBox1.Text += val + Environment.NewLine;
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
}
'''
If you use spL.ReadLine() to read data, you must add a new line ("\n") at the end of your data.
ex: spL.Write("your transmitte data \n");
Solution: Try to replace with spL.ReadLine() with spL.ReadExisting()
So i'm building a snmp trap receiver to receive snmp trap messages.
i'm using the sharpsnmp-net package from lexstudios aswell as the sample.engine with pipline from github.
I'm creating a simple wpf application to just show messages on screen for testing all in .net 4.7.1.
So for the listening part i roughly used the sample snmpd.
public partial class MainWindow : Window
{
private SnmpEngine _engine;
private const string StrAllUnassigned = "All Unassigned";
public MainWindow()
{
var store = new ObjectStore();
store.Add(new SysDescr());
store.Add(new SysObjectId());
store.Add(new SysUpTime());
store.Add(new SysContact());
store.Add(new SysName());
store.Add(new SysLocation());
store.Add(new SysServices());
store.Add(new SysORLastChange());
store.Add(new SysORTable());
store.Add(new IfNumber());
store.Add(new IfTable());
var users = new UserRegistry();
users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
if (DESPrivacyProvider.IsSupported)
{
users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
new MD5AuthenticationProvider(new OctetString("authentication"))));
}
if (AESPrivacyProviderBase.IsSupported)
{
users.Add(new OctetString("aes"), new AESPrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
users.Add(new OctetString("aes192"), new AES192PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
users.Add(new OctetString("aes256"), new AES256PrivacyProvider(new OctetString("privacyphrase"), new MD5AuthenticationProvider(new OctetString("authentication"))));
}
var getv1 = new GetV1MessageHandler();
var getv1Mapping = new HandlerMapping("v1", "GET", getv1);
var setv1 = new SetV1MessageHandler();
var setv1Mapping = new HandlerMapping("v1", "SET", setv1);
var getnextv1 = new GetNextV1MessageHandler();
var getnextv1Mapping = new HandlerMapping("v1", "GETNEXT", getnextv1);
var v1 = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
var membership = new ComposedMembershipProvider(new IMembershipProvider[] { v1 });
var handlerFactory = new MessageHandlerFactory(new[]
{
getv1Mapping,
setv1Mapping,
getnextv1Mapping
});
var pipelineFactory = new SnmpApplicationFactory(new RollingLogger(), store, membership, handlerFactory);
_engine = new SnmpEngine(pipelineFactory, new Listener { Users = users }, new EngineGroup());
_engine.ExceptionRaised += (sender, e) => MessageBox.Show(e.Exception.ToString());
InitializeComponent();
txtIp.Text = #"162"; //port to receive snmp trap
cmbIp.Items.Add(StrAllUnassigned);
foreach (IPAddress address in Dns.GetHostEntry(string.Empty).AddressList.Where(address => !address.IsIPv6LinkLocal))
{
cmbIp.Items.Add(address);
}
cmbIp.SelectedIndex = 0;
}
public void StartListeners()
{
try
{
_engine.Listener.ClearBindings();
int port = int.Parse(txtIp.Text, CultureInfo.InvariantCulture);
/*
if (cmbIp.Text == StrAllUnassigned)
{
if (Socket.OSSupportsIPv4)
{
_engine.Listener.AddBinding(new IPEndPoint(IPAddress.Any, port));
}
if (Socket.OSSupportsIPv6)
{
_engine.Listener.AddBinding(new IPEndPoint(IPAddress.IPv6Any, port));
}
_engine.Start();
if (_engine.Active)
{
MessageBox.Show("Engine activated");
}
return;
}
*/
IPAddress address = IPAddress.Parse(cmbIp.Text);
if (address.AddressFamily == AddressFamily.InterNetwork)
{
if (!Socket.OSSupportsIPv4)
{
MessageBox.Show(Listener.ErrorIPv4NotSupported);
return;
}
_engine.Listener.AddBinding(new IPEndPoint(address, port));
_engine.Listener.MessageReceived += Listener_MessageReceived;
_engine.Start();
if (_engine.Active)
{
MessageBox.Show("Engine activated");
}
return;
}
if (!Socket.OSSupportsIPv6)
{
MessageBox.Show(Listener.ErrorIPv6NotSupported);
return;
}
_engine.Listener.AddBinding(new IPEndPoint(address, port));
_engine.Start();
}
catch (Exception ex)
{
MessageBox.Show("Exception has been thrown in start: " + ex);
}
}
private void Listener_MessageReceived(object sender, MessageReceivedEventArgs e)
{
MessageBox.Show("message received");
}
private void StopListeners()
{
_engine.Stop();
_engine.Dispose();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
//send trap
IPAddress ip = IPAddress.Parse("127.0.0.1");
Messenger.SendTrapV1(
new IPEndPoint(ip, 162),
IPAddress.Loopback, // here should be IP of the current machine.
new OctetString("public"),
new ObjectIdentifier(new uint[] { 1, 3, 6 }),
GenericCode.ColdStart,
0,
0,
new List<Variable>());
}
private void Start_Click(object sender, RoutedEventArgs e)
{
try
{
StartListeners();
}
catch (PortInUseException ex)
{
MessageBox.Show(#"Port is already in use: " + ex.Endpoint, #"Error");
}
}
private void stop_Click(object sender, RoutedEventArgs e)
{
if (_engine.Active)
{
try
{
_engine.Listener.MessageReceived -= Listener_MessageReceived;
StopListeners();
}
catch (Exception ex)
{
MessageBox.Show("exception in stop: " + ex);
}
}
}
}
So to receive snmp trap messages you also got to send one.
I have got a textbox with port number combobox with ip address.
a send trap button and start and stop button.
Send a trap works perfectly i can verify in wireshark i do have a snmp packet however icmp answer with port unreachable which means no one is listening.-> issue 1
When activating the engine i don't have any errors but regarding the icmp i checked in cmd with command : netstat -an to check if something was listening on port 162 but bad luck.
How can i verify the engine is working and or something is listening?
I subscribed to the message_received event but i don't receive anything which could lead to the fact that no one is listening.
And last but not least when I press the stop button i do get a socketexception, but don't receive any of my own messages from try catch loops -> Should I assume this is in the package?
How to solve this problem. I want just to receive snmpv1 trap messages and the store them in a datatable so far.
Event not firing in following code:
private WebSocketSharp.WebSocket client;
private void GetWebsocketFeedMessages()
{
string host = "wss://ws-feed.gdax.com";
client = new WebSocket(host);
client.Connect();
client.OnOpen += client_OnOpen;
client.OnMessage += client_OnMessage;
}
void client_OnMessage(object sender, MessageEventArgs e)
{
string response = e.Data;
}
void client_OnOpen(object sender, EventArgs e)
{
client.Send("{ \"type\": \"subscribe\", \"product_ids\": [ \"ETH-USD\" ] }");
}
I am using vs2012 framework 4.5 and windows application. But not able to reach the line in open and messages events. Not ure what mistake I am making, can anybody please advise?
First, you should setup events and after that call connect method, because it works synchronously.
private void GetWebsocketFeedMessages()
{
string host = "wss://ws-feed.gdax.com";
client = new WebSocket(host);
client.OnOpen += client_OnOpen;
client.OnMessage += client_OnMessage;
client.Connect();
}
I have a problem in my hands.
I have a program in which the client (form1) has to try to reconnect whenever it can not connect to the server.
The loop that I have to do the reconnection is inside the Fomr_load so that the reconnection is automatic.
But the problem is that the application does not open until form_load is complete.
Who knows where I'm goin tell me please
private void Form1_Load(object sender, EventArgs e)
{
Client = new TcpClient();
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
try
{
Socket Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(IP_End);
if (Client.Connected)
{
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
else
{
reconnect();
}
}
catch (SocketException)
{
reconnect();
}
}
private void reconnect()
{
try
{
IPEndPoint IP_End = new IPEndPoint(IPAddress.Parse("192.168.254.38"), 100);
Client.Connect(IP_End);
STW = new StreamWriter(Client.GetStream());
STR = new StreamReader(Client.GetStream());
STW.AutoFlush = true;
backgroundWorker1.RunWorkerAsync();
backgroundWorker1.WorkerSupportsCancellation = true;
}
catch (SocketException)
{
reconnect();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (Client.Connected)
{
try
{
receive = STR.ReadLine();
label1.Invoke(new MethodInvoker(delegate () { label1.Text = (receive + "\n\r"); }));
receive = "";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
Have a boolean variable that you set to true once you connect successfully and then check that as well before calling reconnect(), so your loop should run once, set connectedSuccessfully = true, then next time it runs it will see that it's true and skip over the call to reconnect(). You probably also want to add a timer to maybe try once again after 1 second, then try again in 5 seconds, then again in 10 etc etc.
i'm newbie in C# serial port...
i have a virtual serial port driver and try this code...
private string strPortData = null;
private void okButton_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
serialPort1.Open();
}
string strPortData= "CMD1";
serialPort1.WriteLine(strPortData);
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
textBox1.Text = serialPort1.ReadLine();
}
but do not serialPort1_DataReceived ever call.
What should i do for call DataReceived?
Try creating a new console application with code similar to the following
void Main()
{
using (SerialPort serialPort1 = new SerialPort("COM1"))
using (SerialPort serialPort2 = new SerialPort("COM2"))
{
serialPort1.DataReceived += (sender, args) => {
Console.WriteLine("COM1 Received: " + serialPort1.ReadLine());
};
serialPort2.DataReceived += (sender, args) => {
Console.WriteLine("COM2 Received: " + serialPort2.ReadLine());
};
serialPort1.Open();
serialPort2.Open();
serialPort1.WriteLine("Hello, COM2!");
Thread.Sleep(200);
}
}
The above code opens both serial ports, sets up the data received events, and sends data through it. If you run that code you should see "COM2 Received: Hello, COM2!" output.