Unable to send data using SimpleTCP - c#

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.

Related

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.

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
}

Serial Port write Timeout error [duplicate]

I use virtual COM ports for testing my program. I want to Serial Write with COM8 and Serial read with COM9. When a want to write the values from textbox1, i get this error:
IOException was unhandled (The parameter is incorrect)
How do i get rid of this?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace Flowerpod_User_Interface
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// show list of valid COM ports
foreach (string s in System.IO.Ports.SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.WriteLine(textBox1.Text);
}
else
{
MessageBox.Show("SerialPort1 is not open");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Connect_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
serialPort1.PortName = comboBox1.SelectedItem.ToString();
serialPort1.Open();
textBox3.Text = "Open";
}
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Random slumpGenerator = new Random();
// Or whatever limits you want... Next() returns a double
int tal = slumpGenerator.Next(1000, 10000);
textBox1.Text = tal.ToString();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void serialPort1_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
if (!serialPortRead.IsOpen)
{
serialPort1.PortName = "COM9";
serialPortRead.Open();
textBox4.Text = serialPortRead.ReadLine();
}
}
}
}
There wasn't any bridge between the two ports which caused the problem. The virtual COM port software tricked me !.

C# program to communicate with a xbee module using COM Ports / Using USB Serial COM Port

I am working a c# program which use the usb serial COM Port to transmit and receive data. The component is XBEE module which I want ot access but the code I wrote dosen't detect any serial port on my Computer. Any one who can help me rectifying my mistake.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApplication3
{
public partial class Test : Form
{
private StringBuilder receivedData = new StringBuilder();
public Test()
{
InitializeComponent();
}
private void Test_Load(object sender, EventArgs e)
{
Array ports = System.IO.Ports.SerialPort.GetPortNames();
for (int x = 0; x <= ports.Length; comboBox1.Items.Add(ports.GetValue(x))) ;
timer1.Start();
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.PortName = comboBox1.Text;
if (!serialPort1.IsOpen)
{
serialPort1.Open();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
private void Test_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
}
}
private void button3_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write(textBox2.Text + "\n\r");
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
receivedData.Append(serialPort1.ReadExisting());
}
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.Text = receivedData.ToString();
}
}
}
You need to set the correct parameters on the serial port to match the settings of the device. Have you installed XCTU? Take note of the settings in the "search for devices" dialog - assuming it does find your device!
For me, I found I actually just needed to set the baud rate:
var serialPort = new SerialPort(portName);
serialPort.BaudRate = 115200;
serialPort.Open();
// win!

Categories