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
Related
I'm currently trying to write Wisco protocol (similar to MODBUS ASCII) out to my digital output devices but faced a problem. If I clicked the ON or Off buttons (see the Image WinForm UI) that already have code to send protocol to my digital output it wouldn't do it.
But in another program where I use a textbox and write the protocol myself then I have to press Enter (If I don't press Enter key it will not work) before clicking send button and it works. What seems to be the problem here?
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 WindowsFormsApp4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = "COM5";
serialPort1.BaudRate = 9600;
serialPort1.DataBits = 8;
serialPort1.Open();
progressBar1.Value = 100;
}
catch (Exception err)
{
MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnClose_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
progressBar1.Value = 0;
}
}
private void btnOn_Click(object sender, EventArgs e)
{
serialPort1.Write("#00WDO1,1");
}
private void btnOff_Click(object sender, EventArgs e)
{
serialPort1.Write("#00WDO1,0");
}
}
}
It turns out I just have to add \r\n to solve this problem.
private void btnSend_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("#00WDO1,1");
serialPort1.Write("\r\n");
}
}
private void button2_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("#00WDO1,0");
serialPort1.Write("\r\n");
}
}
I´m programming a client/server application in c#
My 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.IO;
using System.Net;
using System.Net.Sockets;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{ }
private void button1_Click(object sender, EventArgs e)
{
///openfile
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
textBox1.Text = file.FileName;
}
}
private void label2_Click(object sender, EventArgs e)
{ }
private void label3_Click(object sender, EventArgs e)
{ }
private void button2_Click(object sender, EventArgs e)
{
//Socket send = new Socket(addressFamily.internetwork,
socketType.stream, protocolType.tcp);
Socket send = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint port = new
IPEndPoint(IPAddress.Parse(ip.Text),int.Parse(Port.Text));
send.Send(port);
}
private void Form1_Load(object sender, EventArgs e)
{ }
private void label4_Click(object sender, EventArgs e)
{ }
private void label3_Click_1(object sender, EventArgs e)
{ }
}
}
and my error is :
Error 2 The best overloaded method match System.Net.Sockets.Socket.Send(System.Collections.Generic.IList>)'
has some invalid arguments C:\Users\Acer\AppData\Local\Temporary
Projects\WindowsFormsApplication1\Form1.cs 53 13 WindowsFormsApplication1
and Error 3 Argument 1: cannot convert from 'System.Net.IPEndPoint'
to
'System.Collections.Generic.IList>' C:\Users\Acer\AppData\Local\Temporary
Projects\WindowsFormsApplication1\Form1.cs 53 23 WindowsFormsApplication1
The IpEndPoint does not belong into the Send method. This method wants data to be transmitted. The EndPoint belongs into the Connect method.
Hence your error message.
You surely want to connect first, before trying to send data:
send.Connect(port);
picture or every files
If you want to send pictures via socket you should have a look at this post
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.
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.
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).