Twitchlib PubSub cant see events - c#

Im trying to listen to predictions and channel point rewards. But PubSub is completely silent and I can't figure out why.
using TwitchLib.PubSub;
using TwitchLib.PubSub.Events;
namespace PubSub_app
{
class PubSub
{
TwitchPubSub client;
public PubSub()
{
client = new TwitchPubSub();
client.OnPubSubServiceConnected += Pubsub_OnPubSubServiceConnected;
client.OnChannelPointsRewardRedeemed += Pubsub_OnChannelPointsRewardRedeemed;
client.OnPrediction += Pubsub_OnPrediction;
client.Connect();
}
private void Pubsub_OnPubSubServiceConnected(object sender, System.EventArgs e)
{
client.ListenToChannelPoints("62651386");
client.ListenToPredictions("62651386");
Console.WriteLine("PubSub Connected");
}
private void Pubsub_OnPrediction(object sender, OnPredictionArgs e)
{
Console.WriteLine("Prediction");
Console.WriteLine(e.Title);
}
private void Pubsub_OnChannelPointsRewardRedeemed(object sender, OnChannelPointsRewardRedeemedArgs e)
{
Console.WriteLine("Points redeemed");
Console.WriteLine(e.RewardRedeemed);
}
}
}
The only thing that console displays that its connected

You are missing the client.SendTopics(accessToken); line in Pubsub_OnPubSubServiceConnected.

Related

Unable to send data using SimpleTCP

I am trying to create a TCP/IP client/server app that runs on my computer.The server seems to works perfectly but the client can't send any data.
Here is my code for the client:
using SimpleTCP;
using System.Text;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// implementing simple tcp client
SimpleTcpClient client;
//SimpleTcpServer server;
private void btnConnect_Click(object sender, EventArgs e)
{
btnConnect.Enabled = false;
// server.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
//btnSend.Enabled = false;
client = new SimpleTcpClient();
client.StringEncoder = Encoding.UTF8;
client.DataReceived += Client_DataReceived;
}
private void Client_DataReceived(object? sender, SimpleTCP.Message e)
{
textStatus.Invoke((MethodInvoker)delegate ()
{
textStatus.Text += e.MessageString;
});
}
private void btnSend_Click(object sender, EventArgs e)
{
client.Write(textMessage.Text);
}
}
}
Here is code for the server:
using SimpleTCP;
using System.Net;
using System.Text;
using System.Windows.Forms;
namespace TCPIPDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
if (server.IsStarted)
{
server.Stop();
}
}
// implementing simpletcpserver class
SimpleTcpServer server;
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13;
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
}
private void Server_DataReceived(object? sender, SimpleTCP.Message e)
{
textStatus.Invoke((MethodInvoker)delegate ()
{
textStatus.Text += e.MessageString;
e.ReplyLine(string.Format("You said:{0}",e.MessageString));
});
}
private void btnStart_Click(object sender, EventArgs e)
{
textStatus.Text += "Server starting ...";
//System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(textHost.Text));
IPAddress ip = IPAddress.Parse(textHost.Text);
server.Start(ip, Convert.ToInt32(textPort.Text));
}
}
}
The error I get is the following:
System.Exception: 'Cannot send data to a null TcpClient (check to see if Connect was called)'
you are missing a call to connect the client to the server, there is a Connect method with arguments to provide address and port
https://github.com/BrandonPotter/SimpleTCP/blob/master/SimpleTCP/SimpleTcpClient.cs#L34
The problem is described quite clearly in the exception. You need to call .Connect(URL, PORT) on a new instance of SimpleTcpClient before using it.
For example:
var client = new SimpleTcpClient().Connect("127.0.0.1", 8910);
The official GitHub has more information, please check their readme.

Receiving back server response towards clients request

Currently I am using WebSocket-Sharp. I am able to connect to the server through my application and I am able to send a Client.Send(Move.HeadNod); to the server on button click. However even though I declared
private WebSocket client;
const string host="ws://localhost:80";
public Form1()
{
InitializeComponent();
client=new WebSocket(host);
client.connect();
Client.OnMessage+=client_OnMessage
}
where:
client_OnMessage(object sender,MessageEventArgs e)
{
textbox1.text=convert.tostring(e);
client.send(move.headleft);
}
I am still unable to get a response from the server and continue sending command afterwards.
Edit
void Client_OnMessage(object sender,MessageEventArgs e)
{
if(e.IsText)
{
edata=e.data;
return;
}
else if(e.IsBinary)
{
Textbox1.Text=Convert.Tostring(e.RawData);
return;
}
}
This is the complete code that works on my machine. Put a break-point in both event handlers to see what happens. Maybe your web socket server throws an exception and you just don't know it:
public partial class Form1 : Form
{
private readonly WebSocket _client;
public Form1()
{
InitializeComponent();
_client = new WebSocket("ws://echo.websocket.org");
_client.OnMessage += Ws_OnMessage;
_client.OnError += Ws_OnError;
_client.Connect();
}
private void Ws_OnError(object sender, ErrorEventArgs e)
{
}
private void Ws_OnMessage(object sender, MessageEventArgs e)
{
if (e.IsText)
{
Invoke(new MethodInvoker(delegate () {
textBox1.Text = e.Data;
}));
}
else if (e.IsBinary)
{
Invoke(new MethodInvoker(delegate () {
textBox1.Text = Convert.ToString(e.RawData);
}));
}
}
private void button1_Click(object sender, System.EventArgs e)
{
_client.Send("Hi");
}
}

Websocket4Net Send Multiple messages

I'm having a problem using WebSocket4Net library.
I have the event websocket_opened and when this event is raised on open if I don't send any messages I have an Exception
System.Exception : You must send data by websocket after websocket is
opened
After I send this message I can't send any other messages. I execute the send command but I have no exceptions and it isn't working and If I check the state the websocket is open
If I close the Socket on the opened event and open it again in the closed_event I can send another message without problems.
So, if I want to send multiple messages I have to disconnect after sending a message and reconnect again to send the next message.
private static void websocket_Opened(object sender, EventArgs e)
{
websocket.Send(msg);
websocket.Close();
}
private static void websocket_Closed(object sender, EventArgs e)
{
websocket.Open();
}
Is this normal? Can you help me with this please?
I had a similar questions when I first time used WebSocket4Net.
A good thing about this library that it has a repository on github with many examples of use (tests). These tests was very helpful for me to understand how it should work.
UPDATE:
I saw Fred's comment below and I think I really need to add an example.
So here is it, I've used this api:
using SuperSocket.ClientEngine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocket4Net;
namespace TestProj
{
public class WebSocketTest
{
static string webSocketUri = "wss://ws.binaryws.com/websockets/v3?app_id=1089";
static void Main(string[] args)
{
var socketManager = new WebSocketManager(webSocketUri);
socketManager.Send("{\"time\": 1}");
socketManager.Send("{\"ping\": 1}");
socketManager.Close();
Console.WriteLine("Console can be closed...");
Console.ReadLine();
}
}
public class WebSocketManager
{
private AutoResetEvent messageReceiveEvent = new AutoResetEvent(false);
private string lastMessageReceived;
private WebSocket webSocket;
public WebSocketManager(string webSocketUri)
{
Console.WriteLine("Initializing websocket. Uri: " + webSocketUri);
webSocket = new WebSocket(webSocketUri);
webSocket.Opened += new EventHandler(websocket_Opened);
webSocket.Closed += new EventHandler(websocket_Closed);
webSocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error);
webSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived);
webSocket.Open();
while (webSocket.State == WebSocketState.Connecting) { }; // by default webSocket4Net has AutoSendPing=true,
// so we need to wait until connection established
if (webSocket.State != WebSocketState.Open)
{
throw new Exception("Connection is not opened.");
}
}
public string Send(string data)
{
Console.WriteLine("Client wants to send data:");
Console.WriteLine(data);
webSocket.Send(data);
if (!messageReceiveEvent.WaitOne(5000)) // waiting for the response with 5 secs timeout
Console.WriteLine("Cannot receive the response. Timeout.");
return lastMessageReceived;
}
public void Close()
{
Console.WriteLine("Closing websocket...");
webSocket.Close();
}
private void websocket_Opened(object sender, EventArgs e)
{
Console.WriteLine("Websocket is opened.");
}
private void websocket_Error(object sender, ErrorEventArgs e)
{
Console.WriteLine(e.Exception.Message);
}
private void websocket_Closed(object sender, EventArgs e)
{
Console.WriteLine("Websocket is closed.");
}
private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
{
Console.WriteLine("Message received: " + e.Message);
lastMessageReceived = e.Message;
messageReceiveEvent.Set();
}
}
}
i think that this will resolve your problem
websocket.Open();
private static void websocket_Opened(object sender, EventArgs e)
{
websocket.Send(msg);
websocket.Close();
}
private static void websocket_Closed(object sender, EventArgs e)
{
//DO SOMETHINGS
}

GSMComm phoneConnected/phoneDisconnected Handlers

Trying to develop small application using GsmComm Library.
At the moment a have some problems with detecting if phone is connected or no.
it's detects when phone is disconnected, but doesn't want to detect phone when is connected back again ...
Any idea why ?
my code:
GsmCommMain gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
gsm.PhoneConnected += new EventHandler(gsmPhoneConnected);
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}
Sorry for late answer. Just noticed your question.
There is no need to use EventHandler for connection. If you want to call some functions after phone/gsm modem is connected you should call them after you opened port and (!) checked whether connection is established using IsConnected() member function in GsmCommMain class.
var gsm = new GsmCommMain(4, 115200, 200);
private void Form1_Load(object sender, EventArgs e)
{
//gsm.PhoneConnected += new EventHandler(gsmPhoneConnected); // not needed..
gsm.PhoneDisconnected += new EventHandler(gsmPhoneDisconnected);
gsm.Open();
if(gsm.IsConnected()){
this.onPhoneConnectedChange(true);
}
}
private delegate void ConnctedHandler(bool connected);
private void onPhoneConnectedChange(bool connected)
{
try
{
if (connected)
{
phoneStatus.Text = "OK";
}
else
{
phoneStatus.Text = "NG";
}
}
catch (Exception exce)
{
logBox.Text += "\n\r" + exce.ToString();
}
}
/*public void gsmPhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { true });
}*/
private void gsmPhoneDisconnected(object sender, EventArgs e)
{
this.Invoke(new ConnctedHandler(onPhoneConnectedChange), new object[] { false });
}

Transmitting data with RS422 in .NET

I'm trying to make a simple application to test the RS422 communications with another computer. Using the RS232 interfaces this program is working smoothly, but with the RS422 is not working, as there is one computer that can't send. To complex the scenario a little bit more, I can communicate through RS422 using a HyperTerminal.
Here is the code:
public partial class MainForm : Form
{
private SerialPort m_port;
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_port = new SerialPort();
m_port.BaudRate = 9600;
m_port.DataBits = 8;
m_port.Parity = Parity.None;
m_port.StopBits = StopBits.One;
m_port.Handshake = Handshake.None;
m_port.Encoding = new ASCIIEncoding();
m_port.ReceivedBytesThreshold = 1;
m_port.DataReceived += DataReceivedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
m_port.WriteLine(m_testBox.Text);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_receivedText.Text += m_port.ReadLine();
}
}
Any help or experience with this technology is appreciated. Thanks!
EDIT
There is a lot of differences between the trace with Portmon of Hyperterminal and the .NET component. There is one of the lines that got my attention as it reefers to the wait mask of the port interruption IOCTL_SERIAL_SET_WAIT_MASK.
With HyperTerminal:
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RLSD ERR
With the .NET SerialPort component
IOCTL_SERIAL_SET_WAIT_MASK Serial0 SUCCESS Mask: RXCHAR RXFLAG CTS DSR RLSD BRK ERR RING
Anybody knows how to change the mask from the component? This is getting deep...
Finally there was a problem in the initialitation and another one with the blocking ReadLine call. RTS and DTS must be enabled.
Here is the code
using System;
using System.IO.Ports;
using System.Text;
using System.Windows.Forms;
namespace ComPlay
{
public partial class MainForm : Form
{
private SerialPort m_port;
private byte [] m_buffer = new byte[10];
public MainForm()
{
InitializeComponent();
m_list.Items.AddRange(SerialPort.GetPortNames());
m_list.SelectedIndex = 0;
m_port = new SerialPort(SerialPort.GetPortNames()[0],9600,Parity.None,8,StopBits.One);
m_port.Handshake = Handshake.None;
m_port.RtsEnable = true;
m_port.DtrEnable = true;
m_port.DataReceived += DataReceivedEvent;
m_port.PinChanged += PinChangedEvent;
}
~MainForm()
{
if (m_port != null)
m_port.Close();
}
private void openClick(object sender, EventArgs e)
{
if (m_port.IsOpen)
m_port.Close();
m_port.PortName = (string)m_list.SelectedItem;
try
{
m_port.Open();
m_buttonSend.Enabled = true;
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
private void ButtonSendClick(object sender, EventArgs e)
{
byte [] r_bytes = Encoding.ASCII.GetBytes(m_testBox.Text);
m_port.Write(r_bytes,0,r_bytes.Length);
}
private void DataReceivedEvent(object sender, SerialDataReceivedEventArgs args)
{
Invoke(new EventHandler(DoUpdate));
}
private void DoUpdate(object s, EventArgs e)
{
m_port.Read(m_buffer, 0, m_buffer.Length);
m_receivedText.Text += Encoding.ASCII.GetString(m_buffer);
}
private void PinChangedEvent(object sender, SerialPinChangedEventArgs args)
{
}
}
}
The important thing to begin transmitting was to change this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000000 Replace:80000040 XonLimit:1024 XoffLimit:1024
to this
IOCTL_SERIAL_SET_HANDFLOW Serial1 SUCCESS Shake:80000001 Replace:80000040 XonLimit:1024 XoffLimit:1024
activating RTS and DTR.

Categories