Receiving back server response towards clients request - c#

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

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.

Twitchlib PubSub cant see events

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.

calling server method in client .net SignalR

I'm a beginner in SignalR. how can I define method in client, and call it from server. here is my code :
in Server :
public class ChatHub : Hub
{
public void ServerMethod()
{
Clients.All.ClientMethod();
}
}
in Client :
HubConnection connection;
IHubProxy proxy;
public MainWindow()
{
InitializeComponent();
connection = new HubConnection("LocalHostDomain");
proxy = connection.CreateHubProxy("ChatHub");
}
private void Call_Click(object sender, RoutedEventArgs e)
{
proxy.Invoke("ServerMethod");
}
private void Start_Click(object sender, RoutedEventArgs e)
{
proxy.On("ClientMethod", () =>
{
tb1.Text = "Hello";
});
connection.Start().Wait();
}
but tb1.Text won't change!! it's very simple, but I don't know how to do it!
The calling thread cannot access this object because a different thread owns it.
SignalR processes the incomming messages in another thread than the UI thread. Changes to the UI must always be performed on the UI thread. Therefore, you need to synchronize access. For example:
private void Start_Click(object sender, RoutedEventArgs e)
{
proxy.On("ClientMethod", () => UpdateLabel());
connection.Start().Wait();
}
private void UpdateLabel()
{
if (InvokeRequired)
{
BeginInvoke(new Action(UpdateLabel));
return;
}
tb1.Text = "Hello";
}
this is how you can do it
private void Start_Click(object sender, RoutedEventArgs e)
{
proxy.On("ClientMethod", () =>
{
change_text("Hello");
});
}
private void change_text(string text)
{
if (tb1.InvokeRequired)
{
tb1.Invoke(new MethodInvoker(delegate { tb1.Text = text; }));
}
else
{
tb1.Text = text;
}
}
you can change the text without having to put it a method. I am just giving you and idea how to do it.

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

WPF: How to write stream which owned by main process in thread?

I want to implement this function: when receive a http request, then create a new window form, and waiting for user inputing response text and write to the http response stream. The quesition is, I can not write response text to the stream in thread even I useing the Action<> delegate. Some code like this:
public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//startup web server
Dispatcher.BeginInvoke(new Action(Start));
}
private void Start()
{
var server = new HttpServer();
try
{
server.EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
server.RequestReceived += DataProcess;
}
catch (Exception ex)
{
return;
}
}
private void DataProcess(object sender, HttpRequestEventArgs e)
{
//create a new window in which user can input the response for the http request e.
var pw = (PrivateWindow)Dispatcher.Invoke(new Func<HttpRequestEventArgs, PrivateWindow>(CreatePrivateWindow), e);
}
public PrivateWindow CreatePrivateWindow(string windowKey, HttpRequestEventArgs e)
{
var pw = new PrivateWindow();
pw.httpRequest = e;//pass the stream to thread here.
windows.Add(pw);
return pw;
}
}
public partial class PrivateWindow : Window
{
private void btnSendMessage_Click(object sender, RoutedEventArgs e)
{
string messageText = new TextRange(txtWriteMessage.Document.ContentStart, txtWriteMessage.Document.ContentEnd).Text.Trim();
//write the response in thread
Dispatcher.BeginInvoke(new Action<HttpRequestEventArgs, string>(WriteToStream), httpRequest, messageText);
}
private void WriteToStream(HttpRequestEventArgs e, string str)
{
//**here occurs "stream can not be written" error.**
using (var writer = new StreamWriter(e.Response.OutputStream))
{
writer.Write(str);
}
}
}

Categories