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.
Related
I'm trying to read data by UDP protocol when press a button, but I can only read the data once after pressing a button. I need to receive this
string of data continuously and insert a LF after CR to fix my string to send another software. Can you help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UdpClient receivingUdpClient = new UdpClient(6009);
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
string returnData = Encoding.ASCII.GetString(receiveBytes);
label2.Text = ASCIIEncoding.ASCII.GetString(receiveBytes);
button1.Enabled = false;
textBox1.Enabled = false;
textBox3.Enabled = false;
button3.Enabled = true;
}
private void label2_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
E.g string
$GPGGA,010147,2258.41941,S,04200.77435,W,2,07,1.4,0.0,M,0.0,M,2.2,0362*56
I was trying to create a Remote Desktop Viewer. In this part of the app, this is where the user would set up their ip and port to be connected by other user. the problem is: everytime i press the connect button it would hit catch(exception) and failed to connect.
Share
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
namespace Remote_Desktop
{
public partial class Form1 : Form
{
private readonly TcpClient client = new TcpClient();
private NetworkStream mainStream;
private int portNumber;
private static Image GrabDesktop()
{
Rectangle bounds = Screen.PrimaryScreen.Bounds;
Bitmap screenshot = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
Graphics graphics = Graphics.FromImage(screenshot);
graphics.CopyFromScreen(bounds.X, bounds.Y, 0, 0,bounds.Size, CopyPixelOperation.SourceCopy);
return screenshot;
}
private void SendDesktopImage()
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
mainStream = client.GetStream();
binaryFormatter.Serialize(mainStream, GrabDesktop());
}
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
portNumber = int.Parse(txtPort.Text);
try
{
client.Connect(txtIp.Text, portNumber);
MessageBox.Show("Connected!");
}
catch(Exception)
{
MessageBox.Show("Failed To Connect!");
}
}
private void btnSend_Click(object sender, EventArgs e)
{
if (btnSend.Text.StartsWith("Share"))
{
timer1.Start();
btnSend.Text = "Stop Sharing";
}
else
{
timer1.Stop();
btnSend.Text = "Share Screen";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
SendDesktopImage();
}
}
}
Any help means a lot thanks! If any problem tell me i will try to fix it!
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.
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();
}
}
}
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).