Chilkat Sockets error WSAECONNRESET in C# 4.0 - c#

my code is working fine but also I am receiving lot of WSAECONNRESET An existing connection was forcibly closed by the remote host. error.
I have a Chilkat.Socket Listener exe which is executing as a windows service and a test program which is simply sending strings data to this listener service. Listener is working fine but the program which is generatring strings and sending it to the listener is receiving the below mentioned error...please guide.
Error:
ChilkatLog:
SendString:
DllDate: Jan 19 2012
UnlockPrefix: XXXXSocket
Username: XXXXXX
Architecture: Little Endian; 64-bit
Language: .NET 4.0 / x64
fd: 0x510
objectId: 1433
NumChars: 111
Charset: ansi
NumBytes: 111
SocketError: WSAECONNRESET An existing connection was forcibly closed by the remote host.
For more information see this Chilkat Blog post: http://www.cknotes.com/?p=217
Error sending on socket
send_size: 111
Failed.
This is my windows service code running as a listner
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft.Json;
namespace Test.Services.MessageServer
{
public partial class MessageProcessor : ServiceBase
{
private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public MessageProcessor()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
init();
}
protected override void OnStop()
{
}
private void init()
{
_socket = new Chilkat.Socket();
_logger.Info("Service starting...");
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//_logger.Info("Service started");
var success = _socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = _socket.BindAndListen(5555, 25);
if (success != true)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
// Get the next incoming connection
// Wait a maximum of 0 seconds (0000 millisec)
Chilkat.Socket connectedSocket = null;
connectedSocket = _socket.AcceptNextConnection(0);
if (connectedSocket == null)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.MaxReadIdleMs = 1000;
string txt = connectedSocket.ReceiveUntilMatch("-EOM-");
_logger.Info(String.Format("Received Orignal Message: {0}", txt));
if (txt == string.Empty)
{
_logger.Error(String.Format("Error: {0}", _socket.LastErrorText));
return;
}
connectedSocket.Close(0);
((BackgroundWorker)sender).ReportProgress(0, txt.Replace("-EOM-", string.Empty).Trim());
}
catch (Exception ex)
{
_logger.Error(String.Format("Error caught: {0}", _socket.LastErrorText));
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState == null) return;
_logger.Info((String.Format("Message Received: {0}", e.UserState.ToString())));
var obj = JsonConvert.DeserializeObject<JsonGeoLocation>(e.UserState.ToString());
_logger.Info((String.Format("Received: JobId: {0}\tDateTime: {1}\tLatitude: {2}\tLongitude: {3}", obj.F0,obj.F1,obj.F2.F0,obj.F2.F1)));
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}
This is my code which is connecting to the above code and sending the messages
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Chilkat;
using NLog;
using Newtonsoft;
using Newtonsoft.Json;
namespace SocketMessageGenerator
{
public partial class Form1 : Form
{
//private Chilkat.Socket _socket;
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
public Form1()
{
InitializeComponent();
Init();
}
private void Init()
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
SendMessage();
}
private void SendMessage()
{
var socket = new Socket();
var success = socket.UnlockComponent("XXXXXXSocket_XXXXXXXXX");
try
{
if (success != true)
{
return;
}
success = socket.Connect("191.111.009.256", 5555, false, 0);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to connect to host: {0}", socket.LastErrorText)));
}
var geoLocation = new JsonGeoLocation { F0 = 123, F1 = System.DateTime.Now, F2 = new JsonGeoPosition { F0 = 51.577790260314941, F1 = 0.0993499755859375 } };
var obj = JsonConvert.SerializeObject(geoLocation);
success = socket.SendString(message);
//success = socket.SendString(obj);
if (!success)
{
_logger.Info((String.Format("Error: \nunable to send message: {0}", socket.LastErrorText)));
}
socket.Close(1000);
}
catch (Exception)
{
throw;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
}
}

Related

Why is my client server udp code not sending?

I have been interested in tcp, udp and named pipes lately and am trying to teach myself. I am trying to get a udp connection set up to see how it works. I have a client and server program in windows form app with a richtextBox1 and btStart. I would like to get this setup on the same computer and then try with two computers. I cannot get anything to send. Can anyone show me what I'm doing wrong? I am just trying to learn.
Here is the server code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPServer
{
public partial class Form1 : Form
{
delegate void ShowMessageMethod(string msg);
UdpClient _server = null;
IPEndPoint _client = null;
Thread _listenThread = null;
private bool _isServerStarted = false;
public Form1()
{
InitializeComponent();
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
this.btStart.Text = "StartServer";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btStart_Click(object sender, EventArgs e)
{
if (_isServerStarted)
{
Stop();
btStart.Text = "StartServer";
}
else
{
Start();
btStart.Text = "StopServer";
}
}
private void Start()
{
//Create the server.
IPEndPoint serverEnd = new IPEndPoint(IPAddress.Any, 1234);
_server = new UdpClient(serverEnd);
ShowMsg("Waiting for a client...");
//Create the client end.
_client = new IPEndPoint(IPAddress.Any, 0);
//Start listening.
Thread listenThread = new Thread(new ThreadStart(Listening));
listenThread.Start();
//Change state to indicate the server starts.
_isServerStarted = true;
}
private void Stop()
{
try
{
//Stop listening.
listenThread.Join();
ShowMsg("Server stops.");
_server.Close();
//Changet state to indicate the server stops.
_isServerStarted = false;
}
catch (Exception excp)
{ }
}
private void Listening()
{
byte[] data;
//Listening loop.
while (true)
{
//receieve a message form a client.
data = _server.Receive(ref _client);
string receivedMsg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the message.
this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" + receivedMsg });
//Send a response message.
data = Encoding.ASCII.GetBytes("Server:" + receivedMsg);
_server.Send(data, data.Length, _client);
//Sleep for UI to work.
Thread.Sleep(500);
}
}
private void ShowMsg(string msg)
{
this.richTextBox1.Text += msg + "\r\n";
}
}
}
Here is the client code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace UDPClient
{
public partial class Form1 : Form
{
UdpClient _server = null;
IPEndPoint _client = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
//Get the server.
_server = new UdpClient("127.0.0.1", 16000);
//Create a client.
_client = new IPEndPoint(IPAddress.Any, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
_server.Close();
}
catch (Exception s)
{
}
}
private void btSend_Click(object sender, EventArgs e)
{
try
{
//Send the input message.
string text = this.richTextBox1.Text;
_server.Send(Encoding.ASCII.GetBytes(text), text.Length, _client);
//Receive the response message.
byte[] data = _server.Receive(ref _client);
string msg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the response message.
this.richTextBox1.Text = msg;
}
catch (Exception exp)
{
}
}
}
}
As a general rule, when you want to check connectivity problems or debug what is being send, you can use a proxy like Fiddler or ZAP, so you are going to be able to intercept the traffic, analyze and manipulate it in case you need, and this is going to give you a lot of information.
As possible solution to your question take a look at Microsoft documentation.

Why I am coming across "Format Exception" while execution in C# TCP/IP Application?

The code is as follows:
The ServerForm Code:
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 SimpleTCP;
namespace TCPIP
{
public partial class ServerForm : Form
{
public ServerForm()
{
InitializeComponent();
}
SimpleTcpServer server;
private void Form1_Load(object sender, EventArgs e)
{
server = new SimpleTcpServer();
server.Delimiter = 0x13; //enter
server.StringEncoder = Encoding.UTF8;
server.DataReceived += Server_DataReceived;
}
private void Server_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
e.ReplyLine(string.Format("You said: {0}",e.MessageString));
});
// throw new NotImplementedException();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void StartButton_Click(object sender, EventArgs e)
{
StatusText.Text += "Server Starting !";
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text)); //error here
server.Start(ip,Convert.ToInt32(PortText.Text));
}
private void StopButton_Click(object sender, EventArgs e)
{
if(server.IsStarted)
{
server.Stop();
}
}
}
}
The Code of the ClientForm is as follows:
using SimpleTCP;
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;
namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SimpleTcpClient client;
private void ConnectButton_Click(object sender, EventArgs e)
{
ConnectButton.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
client = new SimpleTcpClient();
client.StringEncoder = Encoding.UTF8;
client.DataReceived += Client_DataReceived;
}
private void Client_DataReceived(object sender, SimpleTCP.Message e)
{
StatusText.Invoke((MethodInvoker)delegate ()
{
StatusText.Text = e.MessageString;
//...
});
//throw new NotImplementedException();
}
private void SendButton_Click(object sender, EventArgs e)
{
client.WriteLineAndGetReply(TextMessage.Text, TimeSpan.FromSeconds(4));
}
}
}
The issue in the above code is that it is 'build'ing correctly and even when I am debug it with the new instance, the code is running fine, but will I debug, as soon as I press the "start" button in the Server form it shows the error in line :
System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(HostText.Text));
The error is: System.FormatException: 'Input string was not in a correct format.'
Please refer the Screenshot for details and suggest a potential fix to the issue.Image of Screenshot of Error inLine
Clearly HostText.Text is returning a value that can't be parsed into a long.
This exception is coming from long.Parse, which is really a language shortcut for Int64.Parse, whose documentation states that it will throw this exception if the input string is not formatted correctly.

Arduino, Visual C# best Serial comunication

I'm new to Arduino and serial ports and I want to make the best communication between Arduino and my C# program. In my code I want to control one or more servo motors fast as possible. This is my Arduino code:
#include <Servo.h>
Servo serv;
void setup() {
Serial.begin(115200);
Serial.setTimeout(5);
pinMode(9,OUTPUT);
serv.attach(9);
}
String msg;
void loop() {
String val = Serial.readString();
if(val!=0) {
if(val.startsWith("U")) {
val.replace("U","");
serv.write(val.toInt());
delay(10);
}
}
if(Serial.available()>0) {
msg = "U";
msg = msg+serv.read();
Serial.println(msg);
}
}
And my C# program:
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 arduino_servo {
public partial class Form1 : Form {
SerialPort port;
public Form1() {
InitializeComponent();
init();
}
private void Form1_Load(object sender, EventArgs e) {
}
private void init() {
port = new SerialPort();
port.PortName = "COM5";
port.BaudRate = 115200;
port.DataReceived += new SerialDataReceivedEventHandler(Primire_date);
try {
port.Open();
}
catch(Exception ex) {
MessageBox.Show("Eroare",ex.Message,MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void trackBar1_Scroll(object sender, EventArgs e) {
if (port.IsOpen) {
port.WriteLine("U"+trackBar1.Value.ToString());
}
}
private void Primire_date(object emitator, SerialDataReceivedEventArgs e) {
string msg = port.ReadLine();
if (msg.IndexOf("U") > -1) {
msg = msg.Replace("U", "");
label1.Text = msg;
}
}
}
}
If you guys could give me some advice or some modifications, I would be very thankful. My communication is a bit laggy.

UDP datagram code for server client application in C#

When i try to send a message from my client , the server is not able to receive that message and print it. Can anyone tell me the error in the following server client application.
I have created two WinForm projects, one is UDP server and the other is UDP client.
In UDP server project, I created a form which contains a RichTextBox named richTextBox1 to show message and a Button named btStart to start/stop the listening. This is the code snippet:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UDPServer
{
public partial class Form1 : Form
{
delegate void ShowMessageMethod(string msg);
UdpClient _server = null;
IPEndPoint _client = null;
Thread _listenThread = null;
private bool _isServerStarted = false;
public Form1()
{
InitializeComponent();
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
this.btStart.Text = "StartServer";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btStart_Click(object sender, EventArgs e)
{
if (_isServerStarted)
{
Stop();
btStart.Text = "StartServer";
}
else
{
Start();
btStart.Text = "StopServer";
}
}
private void Start()
{
//Create the server.
IPEndPoint serverEnd = new IPEndPoint(IPAddress.Any, 1234);
_server = new UdpClient(serverEnd);
ShowMsg("Waiting for a client...");
//Create the client end.
_client = new IPEndPoint(IPAddress.Any, 0);
//Start listening.
Thread listenThread = new Thread(new ThreadStart(Listening));
listenThread.Start();
//Change state to indicate the server starts.
_isServerStarted = true;
}
private void Stop()
{
try
{
//Stop listening.
listenThread.Join();
ShowMsg("Server stops.");
_server.Close();
//Changet state to indicate the server stops.
_isServerStarted = false;
}
catch (Exception excp)
{ }
}
private void Listening()
{
byte[] data;
//Listening loop.
while (true)
{
//receieve a message form a client.
data = _server.Receive(ref _client);
string receivedMsg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the message.
this.Invoke(new ShowMessageMethod(ShowMsg), new object[] { "Client:" + receivedMsg });
//Send a response message.
data = Encoding.ASCII.GetBytes("Server:" + receivedMsg);
_server.Send(data, data.Length, _client);
//Sleep for UI to work.
Thread.Sleep(500);
}
}
private void ShowMsg(string msg)
{
this.richTextBox1.Text += msg + "\r\n";
}
}
}
In UDP client project, I also created a form which contains a RichTextBox named richTextBox1 to input or show message and a Button named btSend to send the input message. You can run several instances of this project. The server would cope with all the running clients. This is the code snippet:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace UDPClient
{
public partial class Form1 : Form
{
UdpClient _server = null;
IPEndPoint _client = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void serverMsgBox_Load(object sender, EventArgs e)
{
//Get the server.
_server = new UdpClient("127.0.0.1", 16000);
//Create a client.
_client = new IPEndPoint(IPAddress.Any, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
_server.Close();
}
catch (Exception s)
{
}
}
private void btSend_Click(object sender, EventArgs e)
{
try
{
//Send the input message.
string text = this.richTextBox1.Text;
_server.Send(Encoding.ASCII.GetBytes(text), text.Length);
//Receive the response message.
byte[] data = _server.Receive(ref _client);
string msg = Encoding.ASCII.GetString(data, 0, data.Length);
//Show the response message.
this.richTextBox1.Text = msg;
}
catch (Exception exp)
{
}
}
}
}
You are not setting your destination. You need to either use UdpClient.Connect before using UdpClient.Send(Byte[], Int32) or use UdpClient.Send(Byte[], Int32, IPEndPoint).

My textbox clear is getting Cannot implicitly convert type

All I want to do is just clear the text box on a button click. I get this error
"Error 2 Cannot implicitly convert type 'string' to 'System.Windows.Forms.TextBox' C:\Users\Ed\Downloads\BT1_B\BT1_B\Form1.cs 108 36 BT1_B
"
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using InTheHand;
using InTheHand.Net;
using InTheHand.Net.Sockets;
using InTheHand.Net.Bluetooth;
namespace BT1_B
{
public partial class Form1 : Form
{
Guid service = new Guid("{00001101-0000-1000-8000-00805F9B34FB}");
BluetoothListener bl;
BluetoothClient bc;
bool radioAvailable = false;
bool listening = false;
delegate void SettbMessageReceivedCallback(string text);
public Form1()
{
InitializeComponent();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
listening = false;
bl.Stop();
}
catch
{
}
}
private void btn_listen_Click(object sender, EventArgs e)
{
try
{
BluetoothRadio.PrimaryRadio.Mode = RadioMode.Discoverable;
radioAvailable = true;
}
catch
{
MessageBox.Show("Please make sure Bluetooth is available");
}
if (radioAvailable)
{
bl = new BluetoothListener(BluetoothService.SerialPort);
bl.Start();
listening = true;
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(ListenLoop));
t.Start();
}
}
private void ListenLoop()
{
try
{
while (listening)
{
bc = bl.AcceptBluetoothClient();
StreamReader sr = new StreamReader(bc.GetStream());
String message = sr.ReadLine();
sr.Close();
SettbMessageReceived(message);
}
}
catch
{
}
}
private void SettbMessageReceived(string text)
{
try
{
if (this.txt_incoming_message.InvokeRequired)
{
SettbMessageReceivedCallback d = new SettbMessageReceivedCallback(SettbMessageReceived);
this.Invoke(d, new object[] { text });
}
else
{
this.txt_incoming_message.Text += text + "\r\n";
}
}
catch (ThreadAbortException ex)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_clear_Click(object sender, EventArgs e)
{
txt_incoming_message.Clear();
}
}
}
private void btn_clear_Click(object sender, EventArgs e)
{
txt_incoming_message.Text = "";
}
but please keep the question specific, and do some research before asking for help.

Categories

Resources