Connecting to Web Socket - c#

I am new to C# sockets.
I am trying to connect to Web Socket, but I am neither getting connected message nor error message and no Exception.
What I need to do to connect with web socket? How can I trace whether it is trying to connect to socket?
My Code:
private WebSocket client;
const string host = "wss://stream.binance.com:9443";
private void button2_Click(object sender, EventArgs e)
{
client = new WebSocket(host);
client.OnOpen += (ss, ee) =>
MessageBox.Show("Concceted");
client.OnError += (SetStyle, ee) =>
MessageBox.Show("error");
client.Connect();
}

I guess you use WebSocketSharp. The following console test program tries to connect to the same url from your question:
using System;
using WebSocketSharp;
namespace Example
{
public class Program
{
public static void Main(string[] args)
{
using (var ws = new WebSocket("wss://stream.binance.com:9443"))
{
ws.OnMessage += (sender, e) =>
Console.WriteLine("Message received" + e.Data);
ws.OnError += (sender, e) =>
Console.WriteLine("Error: " + e.Message);
ws.Connect();
Console.ReadKey(true);
}
}
}
}
When I run it i get the following console output:
Fatal|WebSocket.doHandshake|Not a WebSocket handshake response.
According to the binance websocket stream documentation you need to change your url to e.g.
wss://stream.binance.com:9443/ws/bnbbtc#ticker
I recommend that you print the content of the error message (in this case e.Message) if possible because it can give you valuable hints to what might be the cause of the error.

Related

Start SCS server from another class (WinForms)

I'm trying to implement a SCS framework server with WinForms in C# but I am having issues making it work. The server standalone works fine when using it in the Main method (no WinForms). I have a client-sided and a server-sided sample code from the SCS framework that I'm trying to implement in WinForms together with some of my own code. It all went well until I decided to try and use WinForms aswell (I had to move the server code to a class of it's own).
I am not getting any errors when I am starting the server, however I can't connect with the client anymore (worked before I moved the server to a class of its own). Client gets System.Net.Sockets.SocketException. On the server-side, I get the error System.InvalidOperationException when the client is trying to connect.
This is my Form1.cs:
using System;
using System.Windows.Forms;
namespace Server_Test
{
public partial class Form1 : Form
{
public static Form1 Self;
Server server = new Server();
public Form1()
{
InitializeComponent();
Self = this;
}
public void rtb1Text(string text)
{
richTextBox1.AppendText(text);
}
public void rtb2Text(string text)
{
richTextBox2.Text = text;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text.EndsWith("Start"))
{
button1.Text = "Stop";
server.ServerInit();
}
else if (button1.Text.EndsWith("Stop"))
{
button1.Text = "Start";
// Does nothing atm
}
}
}
}
And this is my Server.cs
using System;
using Hik.Communication.Scs.Communication.EndPoints.Tcp;
using Hik.Communication.Scs.Communication.Messages;
using Hik.Communication.Scs.Server;
namespace Server_Test
{
class Server
{
public void ServerInit()
{
// Create a server that listens 10085 TCP port for incoming connections
var server = ScsServerFactory.CreateServer(new ScsTcpEndPoint(10085));
// Register events of the server to be informed about clients
server.ClientConnected += Server_ClientConnected;
server.ClientDisconnected += Server_ClientDisconnected;
// Start the server
server.Start();
// Form1.Self.rtb1Text("Server has been started successfully.\n");
Console.WriteLine("Server has been started successfully.\n");
}
static void Server_ClientConnected(object sender, ServerClientEventArgs e)
{
Form1.Self.rtb1Text("A new client with ID: " + e.Client.ClientId + " has connected.\n");
// Register to MessageReceived event to receive messages from new client
e.Client.MessageReceived += Client_MessageReceived;
}
static void Server_ClientDisconnected(object sender, ServerClientEventArgs e)
{
Form1.Self.rtb1Text("A client is disconnected! Client Id = " + e.Client.ClientId + "\n");
}
static async void Client_MessageReceived(object sender, MessageEventArgs e)
{
var message = e.Message as ScsTextMessage; // Server only accepts text messages
if (message == null)
{
return;
}
//Get a reference to the client
var client = (IScsServerClient)sender;
Form1.Self.rtb1Text("Client (ID:" + client.ClientId + ") sent a request: " + message.Text + "\n");
switch (message.Text)
{
case "api":
HttpPost httpPost = new HttpPost();
var apiResponse = await httpPost.SendPost("robot_info");
//Send reply message to the client
client.SendMessage(
new ScsTextMessage(
apiResponse,
message.MessageId //Set first message's id as replied message id
));
break;
default:
break;
}
}
}
}
My guess is that I'm doing something wrong when creating a new instance of the Server class and how I'm initializing/starting the server. Might be something else though, I've tried debugging but it didn't make me any smarter.
Any ideas?

MQTT Recived Message ID in C#

Hello I am new to this but I am developing a client to Mosquitto broker.
It works fine, but I want to know how could I add the Sender Id to the message.
i.e. Message From "Client1" : "LightON"
This is how I handle the subscription
private void Form1_Load_1(object sender, EventArgs e)
{
try
{
IPAddress HostIP;
HostIP = IPAddress.Parse(textBox1.Text);
clientSub = new MqttClient(HostIP);
clientSub.MqttMsgPublishReceived += new MqttClient.MqttMsgPublishEventHandler(EventPublished);
}
catch (InvalidCastException ex)
{
MessageBox.Show("ERROR ON LOAD" + ex.ToString());
}
}
The Publish Event is :
private void EventPublished(Object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
try
{
SetText("Recevied Message..");
SetText("The Topic is:" + e.Topic);
SetText("*Message: " + System.Text.UTF8Encoding.UTF8.GetString(e.Message));
SetText("");
}
catch (InvalidCastException ex)
{
}
}
And I am using the M2mqtt library.
The only way to do this is to add it to the message payload yourself.
There is no concept of a publisher id in the MQTT headers. Client IDs are only to identify clients to the broker, not end to end.

WebsocketSharp events not firing

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();
}

Sending data via sockets from c# to a node socket.io server

I am currently trying to feed my socket.io server with data from my C# client. But I am not sure how to receive the message on the server.
My server code:
const io = require('socket.io')(9000);
io.on('connection', (socket) => {
console.log('Connected');
}
First of all I don't know which event I have to listen to, but nevertheless I am unable to send data to my server using the following client (which uses Websocket-sharp) code:
private void init()
{
// start socket connection
using (var ws = new WebSocket("ws://localhost:9000/socket.io/?EIO=2&transport=websocket"))
{
ws.OnMessage += (sender, e) =>
API.consoleOutput("Message: " + e.Data);
ws.OnError += (sender, e) =>
API.consoleOutput("Error: " + e.Message);
ws.Connect();
ws.Send("server");
}
}
The connection works, but how do I receive the message of the server? The sending does not fire an error, therefore I think it does work.
I've gotten this working for a UWP app that connects to a node.js server. Basically what I do is connect to a URL that looks like ws://localhost:4200/socket.io/?EIO=3&transport=websocket
the port number being something we chose.
once that is set I connect to the node.js socket io library via the following lines of code.
private async Task ConnectWebsocket() {
websocket = new MessageWebSocket();
Uri server = new Uri(WebSocketURI); //like ws://localhost:4300/socket.io/?EIO=3&transport=websocket
websocket.Control.MessageType = SocketMessageType.Utf8;
websocket.MessageReceived += Websocket_MessageReceived;
websocket.Closed += Websocket_Closed;
try {
await websocket.ConnectAsync(server);
isConnected = true;
writer = new DataWriter(websocket.OutputStream);
}
catch ( Exception ex ) // For debugging
{
// Error happened during connect operation.
websocket.Dispose();
websocket = null;
Debug.Log("[SocketIOComponent] " + ex.Message);
if ( ex is COMException ) {
Debug.Log("Send Event to User To tell them we are unable to connect to Pi");
}
return;
}
}
`
at this point your socket io on "connection" should fire on your server
then you can emit events to it like normal. except the C# socket code does not discriminate various channels so you must do so on your own. below is how we do it (aka SocketData and SocketIOEvent are classes we have defined)
private void Websocket_MessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) {
try {
using ( DataReader reader = args.GetDataReader() ) {
reader.UnicodeEncoding = UnicodeEncoding.Utf8;
try {
string read = reader.ReadString(reader.UnconsumedBufferLength);
//read = Regex.Unescape(read);
SocketData socc = SocketData.ParseFromString(read);
if (socc != null ) {
Debug.Log(socc.ToString());
SocketIOEvent e = new SocketIOEvent(socc.channel, new JSONObject( socc.jsonPayload));
lock ( eventQueueLock ) { eventQueue.Enqueue(e); }
}
}
catch ( Exception ex ) {
Debug.Log(ex.Message);
}
}
} catch (Exception ex ) {
Debug.Log(ex.Message);
}
}
in our specific application we did not need to send messages to our server, so for that I do not have a good answer.

how to call received data in Serial Port C#

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.

Categories

Resources