Creating an app with C#: hits catch(exeption) everytime - c#

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!

Related

How to make two forms receive information from the serial port that receives information from Arduino?

I am developing a graphical interface that reads variables from different sensors that arrive through the serial port, so far I have managed to read all the variables with a single form but now I want to have two forms.
The first form asks the user to choose the COM and confirms whether the connection was successful or not. Once the connection is successful, the second form is opened where the variables from the sensors will be shown in "labels", the readings sent from Arduino are read by the serial port and stored in an array:
data[0], data[1], data[2] etc...
This is the first form where Serialport1 is found and the data arrives through the serialPort1_DataReceived event:
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;
using System.Media;
namespace AUTOCLAVES_GUI
{
public partial class GUI_AUTOCLAVES_GENERADOR_DE_VAPOR : Form
{
/*VARIABLES GLOBALES*/
string puerto_seleccionado;
public GUI_AUTOCLAVES_GENERADOR_DE_VAPOR()
{
InitializeComponent();
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private void Salir_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Minimizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Minimized;
}
private void Maximizar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
Maximizar.Visible = false;
Restaurar.Visible = true;
}
private void Restaurar_Click(object sender, EventArgs e)
{
WindowState = FormWindowState.Normal;
Restaurar.Visible = false;
Maximizar.Visible = true;
}
private void MenuSideBar_Click(object sender, EventArgs e)
{
if (Sidebar.Width == 270)
{
Sidebar.Visible = false;
Sidebar.Width = 68;
SidebarWrapper.Width = 90;
LineaSidebar.Width = 68;
AnimacionSidebar.Show(Sidebar);
}
else
{
Sidebar.Visible = false;
Sidebar.Width = 270;
SidebarWrapper.Width = 300;
LineaSidebar.Width = 268;
AnimacionSidebarBack.Show(Sidebar);
}
}
private void bunifuFlatButton8_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();
serialPort1.Dispose();
serialPort1.Open();
CheckForIllegalCrossThreadCalls = false;
label2.Text = "CONEXIÓN EXITOSA";
label2.ForeColor = Color.Green;
label2.Font = new Font(label2.Font, FontStyle.Bold);
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
catch
{
label2.Text = "CONEXIÓN FALLIDA";
label2.ForeColor = Color.Red;
label2.Font = new Font(label2.Font, FontStyle.Bold);
MessageBox.Show("REVISE CONEXIÓN DE ARDUINO", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
puerto_seleccionado = comboBox1.Text;
serialPort1.PortName = puerto_seleccionado;
}
private void bunifuFlatButton7_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
label2.Text = "SIN CONEXIÓN";
label2.ForeColor = Color.White;
string[] puertos = SerialPort.GetPortNames();
foreach (string mostrar in puertos)
{
comboBox1.Items.Add(mostrar);
}
}
private Form activeForm = null;
private void openChildForm(Form childForm)
{
if (activeForm != null)
activeForm.Close();
activeForm = childForm;
childForm.TopLevel = false;
childForm.FormBorderStyle = FormBorderStyle.None;
childForm.Dock = DockStyle.Fill;
panel1.Controls.Add(childForm);
panel1.Tag = childForm;
childForm.BringToFront();
childForm.Show();
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
openChildForm(new MUESTREO_EN_TIEMPO_REAL());
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string[] data = serialPort1.ReadLine().Split(',');
if (data.Length > 10)
{
}
else
{
MessageBox.Show("Intente nuevamente", "ADVERTENCIA", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
}
}
}
}
Here is my second form:
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 AUTOCLAVES_GUI
{
public partial class MUESTREO_EN_TIEMPO_REAL : Form
{
public MUESTREO_EN_TIEMPO_REAL()
{
InitializeComponent();
}
private void MUESTREO_EN_TIEMPO_REAL_Load(object sender, EventArgs e)
{
}
private void Salir_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope someone can help me overcome this problem.

Automatically auto-check every new item in a checkedboxlist in c#

I am trying to auto check every new item in my checkedboxlist I have a button that does that it will auto select all, but we don't want it that way to be controlled by a button. we want it so for every new item we get automatically will get checked.
This is my button that auto select all if there are new 20 items this will auto select all and then submit those new items
Here is the code it works but is not I want I want to auto select for every new items coming in, because I have another process that will keep adding new items to the checkedboxlist, also the lst_BarcodeScanEvents is the checkedboxlist name
private void btn_SelectALLScans_Click(object sender, EventArgs e)
{
for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
{
lst_BarcodeScanEvents.SetItemChecked(i, true);
}
}
I checked other sources like google and stackoverflow but I could not find anything to my request here.
Here is the main class where I have the logic of buttons, checkedlistbox and more. and the button method btn_ConnectT_Click calls the methods from the second class
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using System.Web;
using BarcodeReceivingApp.Core.Domain;
using BarcodeReceivingApp.Functionality;
namespace BarcodeReceivingApp
{
public partial class BarcodeReceivingForm : Form
{
//GLOBAL VARIABLES
private const string Hostname = "myip";
private const int Port = 23;
private TelnetConnection _connection;
private ParseReceivingBarcode _parseReceivingBarcode;
private ButtonsDisplay _buttonsDisplay;
public BarcodeReceivingForm()
{
InitializeComponent();
//FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
private void btn_ConnectT_Click(object sender, EventArgs e)
{
_connection = new TelnetConnection(Hostname, Port);
_connection.ServerSocket(Hostname, Port, this);
}
private void btn_StopConnection_Click(object sender, EventArgs e)
{
_connection.Exit();
}
private void btn_RemoveItemFromListAt_Click(object sender, EventArgs e)
{
if (lst_BarcodeScanEvents.CheckedItems.Count != 0)
for (var i = lst_BarcodeScanEvents.CheckedItems.Count; i > 0; i--)
lst_BarcodeScanEvents.Items.RemoveAt(lst_BarcodeScanEvents.CheckedIndices[i - 1]);
else
MessageBox.Show(#"Element(s) Not Selected...");
}
private void BarcodeReceivingForm_Load(object sender, EventArgs e)
{
_buttonsDisplay = new ButtonsDisplay(this);
_buttonsDisplay.ButtonDisplay();
}
private void btn_ApplicationSettings_Click(object sender, EventArgs e)
{
var bcSettingsForm = new BarcodeReceivingSettingsForm();
bcSettingsForm.Show();
}
private void btn_ClearBarcodeList_Click(object sender, EventArgs e)
{
lst_BarcodeScanEvents.Items.Clear();
}
private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
{
MessageBox.Show(#"Item was added at index " + e.Index + #" and the value is " + lst_BarcodeScanEvents.Items[e.Index].ToString());
}
private void btn_SubmitData_Click(object sender, EventArgs e)
{
var receivingFullBarcode = new List<string>();
_connection.GetBarcodeList();
}
private void btn_SelectALLScans_Click(object sender, EventArgs e)
{
for (var i = 0; i < lst_BarcodeScanEvents.Items.Count; i++)
{
lst_BarcodeScanEvents.SetItemChecked(i, true);
}
}
}
}
Here is the second class where I use a telnet port 23 that scan barcodes where and puts it to the checkedlistbox, now the main emethods here that inserts the data to the checkedlistbox is the method serversocket and the readwrite method
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace BarcodeReceivingApp.Functionality
{
public class TelnetConnection
{
private Thread _readWriteThread;
private TcpClient _client;
private NetworkStream _networkStream;
private string _hostname;
private int _port;
private BarcodeReceivingForm _form;
private bool _isExiting = false;
public TelnetConnection(string hostname, int port)
{
this._hostname = hostname;
this._port = port;
}
public void ServerSocket(string ip, int port, BarcodeReceivingForm f)
{
this._form = f;
try
{
_client = new TcpClient(ip, port);
}
catch (SocketException)
{
MessageBox.Show(#"Failed to connect to server");
return;
}
_networkStream = _client.GetStream();
_readWriteThread = new Thread(ReadWrite);
//_readWriteThread = new Thread(() => ReadWrite(f));
_readWriteThread.Start();
}
public void Exit()
{
_isExiting = true;
}
public void ReadWrite()
{
do
{
var received = Read();
if (received == null)
break;
if (_form.lst_BarcodeScanEvents.InvokeRequired)
{
var received1 = received;
_form.lst_BarcodeScanEvents.Invoke(new MethodInvoker(delegate
{
_form.lst_BarcodeScanEvents.AddItem(received1 + Environment.NewLine);
}));
}
} while (!_isExiting);
//var material = received.Substring(10, 5);
//_form.label5.Text += string.Join(Environment.NewLine, material);
CloseConnection();
}
public List<string> GetBarcodeList()
{
var readData = new List<string>();
foreach (string list in _form.lst_BarcodeScanEvents.Items)
{
readData.Add(list);
MessageBox.Show(list);
}
return readData;
}
public string Read()
{
var data = new byte[1024];
var received = "";
var size = _networkStream.Read(data, 0, data.Length);
if (size == 0)
return null;
received = Encoding.ASCII.GetString(data, 0, size);
return received;
}
public void CloseConnection()
{
MessageBox.Show(#"Closed Connection",#"Important Message");
_networkStream.Close();
_client.Close();
}
}
}
so now like I said before for every new items it gets inserted to the checkedlistbox I want it to be auto selected everytime it adds a new data to the checkedlistbox.
The problem, usually simple, of setting the Checked state of a newly added Item of a CheckedListBox, was somewhat complicated because of the nature of the Listbox in question.
The CheckedListBox is a Custom Control with custom events and properties.
It's actually a relatively common customization (one implementation can be see in this MSDN Forum post:
Have ListBox an event when addid or removing Items?) but it might complicate the interpretation of the events.
The Custom Control, when adding a new Item to the List (from a class other than the Form that hosts the Control), raises the custom ItemAdded event
private void [CheckedListBox]_ItemAdded(object sender, ListBoxItemEventArgs e)
The Index of the Item added is referenced by the e.Index property of the custom ListBoxItemEventArgs object.
With the code provided, it can be determined that this event handler is the natural place where the Checked state of the new Item can be set:
private void lst_BarcodeScanEvents_ItemAdded(object sender, ListBoxItemEventArgs e)
{
lst_BarcodeScanEvents.SetItemChecked(e.Index, true);
}
For that I suggest to create an event that you subscribe after you InitializeComponent() of your form like so :
public Form1()
{
InitializeComponent();
lst_BarcodeScanEvents.ControlAdded += new ControlEventHandler(AddedNewSelect);
}
private void AddedNewSelect(object sender, ControlEventArgs e)
{
lst_BarcodeScanEvents.SetItemChecked(e.Control.TabIndex, true);
}

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.

EDSDK EdsSetPropertyData trouble

In visual studio I have a program that currently takes 5 pictures everytime you click the button. I want the program to take those 5 pictures then change the Aperture setting and take 1 last picture.
There isn't really relevant code, so this is for someone who already understands the SDK.
I've already looked around quite a bit for how to handle this, but I'm rather inexperienced with coding in general.
Thanks!
maybe useful code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using EDSDKLib;
using CanonCameraAppLib;
using CanonCameraAppLib.Remote;
namespace CanonCameraApp
{
public partial class CanonCameraApp : Form
{
public delegate void TakePhotoDelegate(int delay);
private CameraAPI api;
private RemoteServer server;
private TakePhotoDelegate takePhotoDelegate;
public CanonCameraApp()
{
InitializeComponent();
api = CameraAPI.Instance;
takePhotoDelegate = new TakePhotoDelegate(takePhotograph);
init();
}
private void server_OnTakePhotoCommandEvent(RemoteCommandEventArgs e)
{
this.Invoke(takePhotoDelegate, e.Delay);
}
private void init()
{
loadCameras();
registerEvents();
if (Convert.ToBoolean(ConfigurationManager.AppSettings["StartServerOnStartup"]))
{
startServerListener();
}
}
private void registerEvents()
{
CameraAPI.OnCameraAdded += new CameraAddedEventHandler(api_OnCameraAdded);
}
private void api_OnCameraAdded(CameraAddedEventArgs e)
{
scanForCamerasToolStripMenuItem_Click(null, new EventArgs());
}
private void startServerListener()
{
server = new RemoteServer(Convert.ToInt32(ConfigurationManager.AppSettings["ListenPort"]));
server.OnTakePhotoCommandEvent += new TakePhoto(server_OnTakePhotoCommandEvent);
new Thread(server.Start).Start();
}
private void loadCameras()
{
try
{
cbCameras.DataSource = api.Cameras;
cbCameras.DisplayMember = "Name";
cbCameras.Enabled = true;
btnTakePhoto.Enabled = true;
btnProperties.Enabled = true;
scanForCamerasToolStripMenuItem.Enabled = false;
subscribeToEvents();
}
catch (CameraNotFoundException)
{
MessageBox.Show("No cameras were detected. Please make sure that they are plugged in and are turned on.");
cbCameras.Enabled = false;
btnTakePhoto.Enabled = false;
btnProperties.Enabled = false;
scanForCamerasToolStripMenuItem.Enabled = true;
}
}
private void subscribeToEvents()
{
List<Camera> cameras = getCameraList();
foreach (Camera camera in cameras)
{
camera.OnNewItemCreated += new CanonCameraAppLib.Events.NewItemCreatedEventHandler(camera_OnNewItemCreated);
}
}
void camera_OnNewItemCreated(Camera sender, CanonCameraAppLib.Events.NewItemCreatedEventArgs e)
{
if (chbPreview.Checked)
{
PhotoPreview preview = new PhotoPreview(e.Item, true);
preview.Show();
}
}
// private void changeAperature(int value)
//{
// Camera camera = getSelectedCamera();
// camera.changeAperture(value);
//}
private void takePhotograph(int delay)
{
Camera camera = getSelectedCamera();
camera.takePhotograph(delay);
}
private Camera getSelectedCamera()
{
return (Camera)cbCameras.SelectedItem;
}
private List<Camera> getCameraList()
{
List<Camera> cameras = new List<Camera>(cbCameras.Items.Count);
foreach (object camera in cbCameras.Items)
{
cameras.Add((Camera)camera);
}
return cameras;
}
#region Handled Form Events
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i <=4; i++)
takePhotograph(Convert.ToInt16(textBox1.Text));
for (int i = 0; i <= 1; i++)
;
}
private void scanForCamerasToolStripMenuItem_Click(object sender, EventArgs e)
{
loadCameras();
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
quit();
}
private void CanonCameraApp_FormClosing(object sender, FormClosingEventArgs e)
{
quit();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
new About().ShowDialog(this);
}
/// <summary>
/// Opens the Camera Properties window
/// </summary>
private void btnProperties_Click(object sender, EventArgs e)
{
new CameraProperties(getSelectedCamera()).Show();
}
#endregion
private void quit()
{
if (server != null)
{
server.Stop();
}
Application.ExitThread();
Application.Exit();
}
}
}
This is what the application it self looks like. There are several dll's and other things involved.

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).

Categories

Resources