
We must have a sound understanding of a few networking concepts before writing a network application’s code.
We’ll start with the term Host.
A host is a fancy term for any computing device connected to a computer network.
This machine can be a laptop, a smartphone, your home router, Amazon Alexa, or a server running in the cloud.
A machine is called a host for a reason.
It is called a host because it is hosting software that can communicate over the network.
Every host on a network is accessible through a unique address within that network.
This address is called Internet Protocol Address, or IP Address for short.
It is written in dotted decimal notation.
A hostname in computer networking is the unique name assigned to a device connected to a network. It is used to identify and distinguish a specific device from other devices on the same network. Host names are commonly used in the Domain Name System (DNS) to map domain names to IP addresses. They are also used in various networking protocols, such as the File Transfer Protocol (FTP) and the Simple Mail Transfer Protocol (SMTP), to establish connections between devices on a network.
In this video, I’ll explain what is an IP address.
We’ll use IP V4 in this course.
Another version of IP specification is IP V6, which is catching up these days.
An IP V4 address is a group of 4 separate 8-bit numbers.
The total length of the IP Address is 32 bits.
An individual number inside the IP Address can have a value between 0 and 255
When printing an IP address, the four numbers are separated by a dot to make reading easier.
This method of printing the IP address is called the dotted decimal notation.
In many cases, a hostname is used instead of an IP address.
A hostname gets translated into an IP address by a Domain Name Server, a.k.a DNS.
An IP address is a unique numeric identifier assigned to each device connected to a network. It allows devices to communicate with each other over the network using a standardized set of rules and protocols. In socket programming, an IP address is often used in conjunction with a port number to establish a connection between two devices. The combination of the IP address and port number is known as a socket. This allows programs to communicate with each other across the network, even if they are running on different devices or operating systems. Overall, IP addresses and socket programming are essential components of modern computer networking, enabling devices to communicate and share information seamlessly.
To understand port numbers, we will use an analogy.
Let’s consider that your PC is like an apartment building.
This building can be reached through a specific street address.
In the case of a PC, it will be the IP address.
This building is further divided into apartments where a unique apartment number identifies every apartment.
This apartment number is similar to the port number.
The computer contains a large but finite number of ports.
Each apartment in this building is occupied by only one thread or process.
Only one thread or process can send or receive data from a port number.
When we need to send data to a specific thread or process, we need to know which port number is being used by it.
We also need to know the PC's IP address on which the thread or the process is running.
The combination of an IP address and a port number is known as an EndPoint.
There are a total of 65536 ports on a computer.
Port numbers from 0 to 1023 are reserved for operating system usage.
You can say the building administration occupies these apartments.
These are called well-known ports or system ports.
A few examples are port 20 is used for FTP.
Port 23 for telnet and port 25 for emails using SMTP.
And port 53 for DNS.
In socket programming and networking, a port number is a unique identifier that helps to direct network traffic to a specific destination. It is a 16-bit integer that ranges from 0 to 65535. The port number is combined with the IP address to create a socket, which is a combination of an IP address and a port number. This socket enables two endpoints to establish a connection and communicate with each other. The port number is used to identify the application or service that is running on the host. For example, HTTP traffic typically uses port 80, while HTTPS traffic uses port 443. Understanding port numbers is crucial for network administrators and software developers who need to configure firewalls, routers, and other network devices to allow traffic to flow smoothly between hosts.
This video compares UDP to TCP/IP, another popular internet communication protocol. Understanding the difference will help you in doing UDP socket programming.
The synonym UDP stands for User Datagram Protocol.
It is a connectionless IP data transfer protocol.
But… what is connectionless?
Lemme explain, in a connectionless protocol, the sender and the receiver don’t need to establish a connection before they can start a data transfer.
For example, if you want to talk to a stranger in real life, you must shake hands and introduce yourself before starting the conversation.
This is the way TCP/IP protocol works.
If you and the stranger were computers communicating through UDP, you wouldn’t need to shake hands and have an introduction. You can start talking.
The heart of user datagram protocol is “the datagram.”
It is the basic unit of data transfer in the UDP
A UDP datagram contains information about the IP address & port number of the host machine which is supposed to receive it and a payload that has to be delivered.
Everything is in binary format and… represented by bytes.
A host computer sends a datagram as one unit, and it is received by the target computer as one unit.
A good example will be like putting a letter in an envelope, writing an address and port number as well on the envelope.
Giving it to the postal service so that the intended receiver would pick it up.
An envelope here is the datagram.
Now let’s talk about a unique UDP capability, Datagram Broadcasting.
Since UDP is a connectionless protocol, as I explained earlier.
No handshakes are needed.
A host can send a packet to all hosts in the network on a specific port number at once in broadcast mode.
This would be akin to picking up a megaphone and talking to everybody in a hall simultaneously.
In the case of broadcast, The IP address part of the datagram is set to all 1s, and a port number is also supplied.
Any other host in the same local area network listening on the specific port number can receive this packet.
It will be akin to putting a letter in an envelope and writing the address “everybody ” on it.
UDP broadcast is a feature used by many network protocols, such as Simple Network Monitoring Protocols or SNMP.
I must also tell you about some other important details of the UDP protocol.
First, the delivery of a datagram is not guaranteed in UDP.
This means the network will not be flooded with re-transmission packets if the client does not receive a packet.
That’s why UDP is used for video and audio conferencing and IP TV applications.
A few missed packets will cause some squeaks in the voice or maybe a few distorted pictures.
But the network won’t be congested with additional packets to ensure you don’t miss a frame while binging on Netflix.
This is different from TCP/IP, in which case there’s an elaborate system of acknowledgments and retransmissions to ensure that all data sent is delivered successfully.
Secondly, the arrival sequence of datagrams on the receiver can be different from the sending sequence.
These characteristics make UDP a faster protocol than TCP/IP.
Anyhow, both TCP/IP and UDP have their areas of application.
Their strengths and weaknesses.
And one size doesn't fit all in this case.
Since we’re already talking about TCP/IP protocol, it is worth mentioning that in the case of TCP/IP protocol, the sender and receiver must establish a connection before they can start a data exchange.
TCP/IP can’t do broadcasting and multicasting.
Multicasting happens when a sender can send one datagram to multiple well-known hosts; this is useful in IPTV scenarios.
Now that you got the basics covered about network programming. Let’s move on to the next section, where we’d crank some code.
We’re going to create a console application project in Visual Studio, let’s do it
I’ll name it UdemyUDPBroadcastSender
In order to write UDP socket based programs
We need to include following namespaces
Let’s add these to the program
using System.Net;
using System.Net.Sockets;
Let’s add these to the program
We are going to use two objects from these namespaces
A Socket object
And an object of IPEndPoint, which is actually a pair of an IP Address and a port number
To practically broadcast the data, we are going to use the method Socket.SendTo
Let’s take a look at the MSDN page of this method
We’re going to use the first method which takes an array of bytes and the IP End Point of the client to which the data will be sent
Any data that we need to send through a socket over the network must be converted into byte format.
We’ll also define a byte array in our program.
We’ll see how that works later in this course.
Let’s move on to the next video and pump some code
I’ll opened the project which we created in last video
I’ll go to the main method
Create an object of Socket, I’ll call it sockBroadcaster
And new it up
We’ll use the constructor that takes three parameters.
Socket sockBroadcaster = new Socket(
AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
The first parameter AddressFamily.InterNetwork means that we’ll be using IP V4.
Second parameter means we’ll be sending datagram and third parameter means we’ll be using UDP protocol.
We need to set the flag “EnableBroadcast” to true since we’ll be using this socket object to send a broadcast.
Next, we’ll create an object of IPEndPoint and name it broadcastEP.
To new this one up I’ll use the constructor that takes two parameters.
The first parameter is the IP Address.
In order to send a broadcast, we will set all values of IP address part of datagram to 1.
That is achieved by using 255.255.255.255
But, the constructor takes an IP Address, that means we can’t just throw a string in there.
Converting a string into an IP Address is very easy
We’re going to call static method IPAddress.Parse and pass it the string containing IP Address.
If the string will contain anything other than an IP Address, an exception will be thrown.
We can use the method IPAddress.TryParse, but right now we know we’re passing in a valid IP address so don’t worry.
The second parameter will be the port number on which we want to send the broadcast.
IPEndPoint broadcastEP = new IPEndPoint(IPAddress.Parse("255.255.255.255"),
23000);
After that, let’s define an array to contain the data we want to broadcast.
byte[] bcBuffer = new byte [] { 0x0D, 0x0A};
Now we’re going to call the method Socket.SendTo
But, let’s bring in a try/catch block before doing that.
Now the method call
sockBroadcaster.SendTo(bcBuffer, broadcastEP);
We’ve passed it the byte array which contains our data and the endpoint where we want the broadcast data to go.
Once we’re done with the send operation, we’ll simply shut down the sender socket and then close it.
sockBroadcaster.Shutdown(SocketShutdown.Both);
sockBroadcaster.Close();
The shutdown method call is going to disable operations on this socket object. Possible values are, send/receive and both.
After disabling communication, we’re going to call the close method which will free any resources associated with this socket object.
We now have a tiny piece of software which can send a broadcast over the network.
But the important questions is, who’s going to receive the broadcast?
In the next video, we’re going to write code for just that.
We’re going to create a console application for the purpose of receiving data on a UDP socket.
Let’s create a console application, I’ll name it UdemyUDPBroadcastReceiver.
First things first, we’ll add the relevant namespaces.
using System.Net;
using System.Net.Sockets;
Next, we’re going to go to the main method and create an object of Socket class just like we did it in the previous video.
If you didn’t see the last video, please watch it. I’ve explained this line of code there.
Next, we’re going to create an IP Endpoint and specify a pair of IP Address and port number on which we’ll receive the data.
Let me explain the parameters
The first parameter means that this socket is going to receive data on all available IP addresses of this host.
A machine might have more than one network interface cards, or software defined IP addresses.
The second parameter means that this socket will receive data on port number 23000.
If you look at the UDP sender code which we wrote earlier, you’ll see that the sender is sending a broadcast to port number 23000.
The port number MUST be same for the sender and receiver to communicate.
Just as we use a byte array to send data, a byte array is again used to receive data as well.
Before we make the Socket.Receive method call, we must first bind the socket to a specific IP End Point on the local machine.
We’ll call the method Socket.Bind for this purpose and supply it the IPEndpoint which we created earlier.
But, let’s create a try/catch block here first.
Now the bind call
sockBroadcaster.Bind(ipep);
This method call is going to associate the supplied IP End Point on the local machine to this socket.
Now we’re going to call the method to receive the data.
sockBroadcaster.Receive(
If you hover the mouse on this method call, you see that it returns an integer.
The description says that “Receives data from a bound socket into a receiver buffer.”
The int return tells us how many bytes of data have been received.
So, we’re going to pass in the receivedBuffer byte array as parameter.
And let’s store the return into an integer.
On the next line, we’re going to print the number of bytes received
I’m not printing the data received on purpose, it involves a few more details which I think are not important right now.
Let’s put the receive call in an infinite loop
And that’s it
Next video, we’re going to put both programs side by side and run them.
I’ve opened both projects side by side
First, I’m going to run the broadcast receiver.
When you’ll run the programs first time, the Windows Firewall is going to show a pop up asking if you want to allow this application to communicate through the network.
Click “Allow Access” on this dialog.
Next, I’ll going to run the broadcast sender
When the broadcast sender runs, we can see that two bytes get received at the receiver end.
We can run the broadcast sender as many times as we like.
Let’s inspect the local variables in the receiver application, right after the receive operation has finished.
I’ll stop the program, put a break point here and run again.
Now let’s run the sender one more time.
Inside the receiver code, let’s take a look at the locals.
I’ll go to “Debug” menu and open “Locals” window
You will see that the first two bytes of the receiveBuffer are set to the data sent by the sender.
These are actually the numeric form of the ASCII characters backslash r backslash n.
Let’s close the receiver and run the sender once again.
I’ll put a break in the Exception block to see if any exception is thrown when nobody receives the data broadcast by the sender.
There’s a lot more that we need to cover and that we are going to cover as you make progress in the course.
So far in the course, we’ve used socket method calls like Send, SendTo, Receive, and ReceiveFrom for UDP socket programming.
A key characteristic of these socket method calls is that they block our program flow.
Our program stops at the point where any of these methods get called.
For example’s sake, I’ve created the application of a new form using the BroadcastReceiver code.
You don’t need to write the code again; that’s why I’ll only show you the working application and not the code details.
The working source code is available in the downloads section of this video.
Let’s run the application.
Before clicking the “Start Receive” button, you’ll notice that I can resize the form, move it around, and even type text on it.
Now I’ll click the “Start Receive” button.
After this, you’ll notice that the application UI becomes unresponsive.
You can’t even close the application; how sick!
This is because the user interface thread is busy in a blocking or synchronous receive network input-output operation.
Let me run the BroadCastSender we created in the last section and send some data.
You’ll notice that the receiver will get all the text.
This is synchronous behavior.
The antonym of synchronous is Asynchronous or non-blocking application.
A long time ago, people used to write code to juggle multiple threads to perform I/O without blocking the UI thread.
Nowadays, it has become relatively simple.
In this course, I’ll show you how to perform UDP socket I/O asynchronously.
So that your application does not block network I/O.
I hope you understand the difference between synchronous and asynchronous applications and want to learn more about creating all glorious asynchronous applications. Do ask all your questions in the Q&A section of the course. I’d love to answer your queries.
You’re going to create your own UDP chat application in this course.
It’s going to be a chatroom-like application(using the network to communicate)
Users will join the chatroom and leave it later, And A user might also send a message to all other users.
A block diagram is shown on the screen.
The application will be divided into multiple projects.
First, there’ll be a class library dll project to house the core logic of the application,
and then there’ll be two user interface projects.
One for the server to which all clients will connect.
And one for the clients.
The library project will be added in both the server and the client such that they may share some standard code.
More than one copy of the client application will run from various machines to communicate with each other.
I’ll head over to the Visual Studio
Let’s create a new solution for the chat server.
I’ll call it UDP Asynchronous Chat
It’s going to be a Windows Class Library.
The class library contains a default class in a file named Class1.cs, I’m going to rename it to UDPAsynchronousChatServer.
Visual Studio is going to rename the class inside of this file automatically.
Next, I’ll add a new project to this solution.
It’s going to be a WinForms project.
Let’s call it UDPChatServerForm
Lastly, I’ll open another copy of Visual Studio and add a new solution application UI here.
I’m going to save these solutions inside the same folder.
Let’s call it UDPChatClientForm
Afterward, let’s add a reference to our library project in both user interface projects.
Let’s build the solution. All looks good; we’ll add more logic to the solution in upcoming videos.
We use UDP socket programming and networking to ensure fast and efficient communication between users.
Before we venture further into asynchronous programming, you must understand what are callback methods.
The need arises from the way UDP related network operations work in .Net.
A special method call is used for asynchronous data transfer using UDP protocol.
Let me show you a block diagram<show block diagram>
So, For example... you might use the method call ReceiveFromAsync.
You offload the network I/O to this method call and move on.
Behind the scenes, this method call can be utilizing the .Net framework thread pool or any other technique, you don’t need to worry.
When the network I/O operation will be completed, the asynchronous I/O method will somehow inform your application code that the job you wanted it to do for your is done.
In case of ReceiveFromAsync method call, some data might have been received.
This is where callback methods come into play.
Callback methods are just “methods”... as the name implies.
These are certain methods inside your custom code, designated to be called back by the API or framework you are using for some purpose.
In our case, A callback method will get called by the sockets library to inform your code that some data has been received.
The sockets API will also provide some other useful data through the parameters of the callback methods.
You as an application developer will have the power to do whatever you want with that information.
<OPEN MSDN PAGE>
Let us open the MSDN page of the Socket.ReceiveFromAsync method and take a look.
This method call, takes a parameter which is an object of a special class, called SocketAsyncEventArgs
The remarks section shows us some properties of the object that must be populated in order to use the method call.
The callback method in this case is supplied by using the property SocketAsyncEventArgs.Completed.
The plus equals to(+=) operator is used to add a callback method to an event.
The callback method name comes at the right hand side.
Let me click this member and open it to see more details.
It says that the value of Completed will be .Net generic EventHandler type
Let’s open EventHandler MSDN page
<Open EventHandler MSDN Page>
All of these things mean that you will need to define a method in your code, which will have the return type void.
And which must take first parameter of type object, and second parameter of a class derived from EventArgs framework.
The EventHandler of SocketAsyncEventArgs mentioned here is going to be a method with the method signature shown on screen in the MSDN page.
Now Let’s go back to the completed event handler MSDN page.
The first parameter will contain the socket on which the event was raised.
The second parameter will contain the status and other information related to the operation completed.
Enough talk talk, now that you know what is an asynchronous method call and what are callback methods, let’s go ahead and add some code to the library project which we created earlier.
UDP sockets in C# are super efficient blazing fast. The UDP protocol allows for fast, low-latency data transfer, making it ideal for applications that require real-time communication. In C#, receiving data on UDP sockets is relatively straightforward. By creating a UdpClient object and binding it to a specific port, we can listen for incoming data from any source. Once data is received, it can be processed and acted upon as needed. Overall, I found working with UDP sockets in C# to be a seamless and effective experience.
Sending images, videos, and audio clips is a common practice in modern chat applications.
The foundational concepts related to transferring these types of media are pretty much the same.
Handling the content is then up to the receIving application, the communication layer is not commonly involved with the consumption of the media.
In this section, we are going to send an image file from one of the connected clients.
The server is going to pass it on to the other clients.
The clients are then going to paint the picture in a picture box.
We are going to modify the ChatPacket class for this purpose.
We are also going to modify the logic in UDP Asynchronous Chat Client class.
Once the class object has received the image, we will need to pass it to the forms application.
For this purpose we’re going to implement a new event ImageReceived
We’ll also define an event handler as well.
So let’s get going!
I’ve opened the Client Form and I am going to add a few controls here.
Those would be a text box for image path, a button to send the image, and a picture box to paint the received picture.
We can add a browse for image dialog here, but that would be a little too fancy I believe.
<Add the controls>
The ids of the controls will be shown on the screen.
<Show control ids>
I will double click the Send Image button.
First, I will add a sanity check to make sure that the file specified exists or not.
if(!File.Exists(tbFileSelectedPath.Text))
{
return;
}
Next, I’ll create an instance of Image class by calling the static method Image.FromFile.
It takes the file path as parameter.
We are going to deal in image files less than 64 KB for learning purposes.
Image imgFile = Image.FromFile(tbFileSelectedPath.Text);
Next, we’re going to write the contents of the file to a memory stream.
Let’s do it in a using block.
using (MemoryStream imageByteStream = new MemoryStream())
{
imgFile.Save(imageByteStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Once the image is saved to an in memory byte stream.
We’re going to call a method on mChatClient for sending the image.
This method does not exist yet and We’re going to define later.
mChatClient.SendImage(
fileName: Path.GetFileName(tbFileSelectedPath.Text),
fileBytes: imageByteStream.ToArray(),
message: tbMessage.Text
);
The first parameter of this imaginary method will be the name of the file.
The second parameter will be an array of bytes, extractracted from imageByteStream which contains the image data we read from the file earlier.
And the final parameter will be any text which the user might want to send alongside the image.
Now I’m going to press Ctrl+. And select generate method.
The method is generated, but it is not implemented yet.
We are going to do that in the next video.
But before that, since we’ll be dealing in large amounts of data. We need to have larger byte array buffers.
Let us search for new byte[] and update the currently present number to 65000.
The statement is present once is server and once in the client.
I’ve opened the UDP Chat Client Form project and the Form1.cs file.
I’ll double click the button titled SendImage
I’m inside the button click event handler for SendImage.
Let’s press F12 and head over to the method we generated in the last video so that we could fill in the details.
First, I’m going to define an object of ChatPacket class.
ChatPacket packImage = new ChatPacket();
We’ll set the packet type to image.
packImage.PacketType = ChatPacket.PACKET_TYPE.IMAGE;
Message will go in message property and file name will go in fileInfo.
packImage.Message = message;
packImage.fileInfo = fileName;
The data bytes read from the file are going to go in RawData.
packImage.RawData = fileBytes;
Let’s get the bytes from the serialized version of the object.
var bytesToSend = Encoding.ASCII.GetBytes(
JsonConvert.SerializeObject(packImage));
SO now we have just a bunch of bytes which we want to send over to the server.
That means we’re going to just construct an object of SocketAsyncEventArgs like we usually do.
SocketAsyncEventArgs saea = new SocketAsyncEventArgs();
saea.SetBuffer(bytesToSend, 0, bytesToSend.Length);
saea.RemoteEndPoint = mChatServerEP;
Let’s save the file name in UserToken for future use.
saea.UserToken = fileName;
The call back will remain the same.
saea.Completed += SendMessageToKnownServerCompletedCallback;
And finally the SendToAsync method call.
mSockBroadCastSender.SendToAsync(saea);
Let’s store the return value and print it along with the SocketError proerty of the SocketAsyncEventArgs object.
Var ret = OnRaisePrintStringEvent(new PrintStringEventArgs( $"Image transfer status, returned: {ret} - Socket Error: {saea.SocketError}"));
This is it for this for the current video, in the next one we’re going to implement the logic for how to paint the picture received over the socket.
Now that our client is capable of sending an image, it is time to pass the raw data recevied , over to the user interface such that it can paint it.
We’re going to go to the UDP Asynchronous Chat Client class.
And to the callback method ReceiveConfirmationCompleted.
This method deserves a better name I believe, let’s rename it.
I will rename it to ReceivedContent and update all references.
Next, I’m going to go towards the bottom of the method and add an else condition.
else if (objPacketConfirmation.PacketType == ChatPacket.PACKET_TYPE.IMAGE){
OnRaiseImageReceived(new ImageReceivedEventArgs(
fileName: objPacketConfirmation.fileInfo,
fileData: objPacketConfirmation.RawData,
message: objPacketConfirmation.Message
));
// add missing here
}
Neither the ImageReceivedEventArgs class nor the OnRaiseImageReceived method exists.
Let’s go ahead and define these.
First of all, the I will click ImageReceivedEventArgs and press ctrl+.
I will select “Generate class in new file”.
Next I will press control + F12 and go inside the newly defined class.
Let’s derive it from EventArgs, I’ll type colon and EventArgs.
And I’ll Ctrl + . and bring in System
And make the class public as well and the member fields public readonly as well.
Now let’s build the solution, an error will be shown saying OnRaiseImageReceived does not exist
Before fixing this, let’s write the line of code which would let us receive more data afterwards.
ReceiveTextFromServer(string.Empty, mChatServerEP as IPEndPoint);
.
I’m going to double click it to go to the source of the error.
Now I’ll hover the mouse over OnRaiseImageReceived and select option “Generate Method”.
Press F12 to go to the newly generated method.
Remove the default throw statement.
In here, we’re going to raise the event just as we did for PrintString in the past.
But first we need to define a public class member EventHandler of ImageReceivedEventArgs.
Public EventHandler<ImageReceivedEventArgs> ImageReceived;
Then I’ll proceed to defining the body of the method OnRaiseImageReceived.
The inner body of the method will be pretty simple, we’ll first create a local variable from the member.
EventHandler<ImageReceivedEventArgs> handler = ImageReceived;
After this, we’ll check the local variable for null and then raise the event.
if (handler != null)
{
handler(this, raiseImageReceivedArgs);
}
Now let’s go to the Forms project and write the subscribe code.
I’m going to the point where we are initializing the mChatClient object and attach the handler.
mChatClient.ImageReceived += chatClient_ImageReceived;
We’re going to define the handler method.
Inside the body of this method, we’ll create an object of a Bitmap.
Since this operation could fail also, we should put a try catch in here.
In catch block, we’ll just show the exception message and move on.
MessageBox.Show(exc.Message);
We’ll be using an object of MemoryStream to reconstruct the bitmap from the bytes received.
using (MemoryStream imageStream = new MemoryStream())Inside the using block, let’s write the value of e.fileData to the imageStream.
imageStream.Write(e.fileData, 0, e.fileData.Length);
Now we can create an object of bitmap from the stream.
bm = new Bitmap(imageStream, false);
Since this operation could fail also, we should put a try catch in here.
SInce this is going to be a cross threaded operation, we’ll need to create a separate method to update the picture box and use it through Invoke method call.
Let’s create an instance of Action of Bitmap and assign it a new method.
Action<Bitmap> updateImage = UpdateImageBox;
Now I’ll generate the right hand side method and go to it’s body.
Inside the method, we’ll assign the picture box the image we want it to display.
pbImageReceived.Image = obj;
We’ll go back to the ImageReceived call back and invoke the method UpdateImageBox.
pbImageReceived.Invoke(updateImage, new Image[] { bm });
Since we know that the user might have sent a message along with the image, let’s print it out as well.
Action<string> print = PrintToTextBox;
tbConsole.Invoke(print, new string[] { e.message});
This is it for the current video, we’re going to have a demo in the next one.
Let’s launch the server.
Next, I’m going to launch multiple instances of the client.
On all clients I’ll change local port numbers and click Broadcast.
Just for the sake of this demo, I’ve created some tiny images which could fit well within our 63 KB limit. <Show Images>
The image Koala-Tiny.jpg is one of those.
You can see these images on screen.
These images will also be available with the source code for you to download.
You’ll need to change the image path according to your own need.
I’m trying to arrange things such that you can see simultaneously when an image is received.
So, I’m going to click “Send Image” button on one of the clients. I can change the message as well.
“Here comes the Koala”.
We can send more than one images this way.
There’s another image, Penguins-Tiny.jpg, I will send it as well.
If the image path is wrong, the form will show an error locally. Let me try that.
What happens if we send a very large image? Well the transfer won’t work.
Now that you have the foundational knowledge about the subject, I suppose you can further explore niche cases on your own.
In this section, we learned how we can transfer JSON encoded byte data over UDP sockets
We wrote the logic to read an image from the disk on the client side.
Convert it into bytes, then encode into JSON using JsonConverter.Serialize and send across the wire.
There were minor changes on the server side. Like buffer size increase to accommodate large amounts of data.
In the client class, we wrote the code to receive an image and pass it on to the consumer.
We added a new event for this purpose.
I hope you found this section to be useful.
In principle, this is the end of the this course.
I might add a few more bonus videos in days to come to cover some more topics as well.
I also teach a course about TCP/IP socket programing here on UDemy. You might find that useful too.
Thanks very much for watching, feel free to ask questions in the Q&A section of the course. Bye.
Welcome to this tutorial on UDP socket programming! This guide will explore the fundamentals of User Datagram Protocol (UDP) socket programming. Whether you are a beginner or an experienced programmer, this tutorial will provide you with a comprehensive understanding of UDP socket programming and how to use it to create efficient network applications. So, let's get started!
UDP, or User Datagram Protocol, is a layer-4 protocol in the OSI model. It is part of the transport layer along with TCP (Transmission Control Protocol). UDP is a connectionless protocol that provides a simple way to send packets of data without the need for a connection. It is often used for applications where speed is more important than reliability, such as video streaming or online gaming. While UDP does not provide any error-checking or retransmission of lost packets, it is still an important part of the OSI model and plays a vital role in many network applications.
This course teaches C# .Net socket programming with UDP sockets in a hands-on and easy fashion. It is a carefully planned and crafted online course that takes the student by the hand and teaches them how to create quality distributed network applications using C# .Net step by step.
In socket programming, connection-less sockets, which include UDP sockets, are often used for applications that require fast and efficient communication. Unlike connection-oriented sockets, which establish a dedicated connection between two endpoints before any data is transmitted, connection-less sockets send data packets to the intended recipient without any prior setup. This makes them ideal for applications prioritizing speed over reliability, such as real-time video streaming or online gaming. However, because there is no guarantee that the packets will arrive in the correct order or even arrive at all, developers must take extra precautions to ensure the accuracy and completeness of their data.
The first sections of this course cover the basics of computer networking and UDP socket programming in CSharp dot Net necessary for network and socket programming.
The following two sections will teach how to send and receive UDP broadcast in a command prompt C# .Net application using synchronous sockets with method calls such as Socket.Send and Socket.Receive. You will also learn how to convert between string and byte data types.
Once you're familiar with distributed network applications, the course takes you toward asynchronous socket programming. You will also learn about callback methods and how you can implement callbacks in C# .Net. I will also show you the publisher-subscriber model, AKA pub/sub model. We will implement the pub/sub model in our library project and the client/server applications using the library as well. We'll create event handlers and delegates and raise events as well.
We will use an Object Oriented approach for this course, following the principles of OOP. The next section will implement a publisher/subscriber model in C# .Net to bridge the gap between the API solution classes and the WinForms-based front end.
Next, you will learn JSON (JavaScript Object Notation) and how to add JSON functionality to your C# applications with Newtonsoft JSON .Net. Finally, we'll start implementing an application-level communication protocol in this section.
In the next section, you'll learn how to transmit binary data over a UDP socket in C# .Net. Then, for example, I will show you how to transfer png image files between multiple clients of your applications through the server. Again, the JSON-based protocol implemented in the previous section will play a key role here.
After watching this short C tutorial course, you can write your own distributed applications that communicate through the network, either WiFi or Ethernet. You will have the foundation knowledge needed to create C# .Net-based applications for IoT, computer telephony, VoIP, online gaming(e.g., Unity), and more.
This course also shows you how to use String Interpolation, a C# 6 feature. You'll also learn how to debug network applications in Visual Studio and write code faster.
You don't need to learn C to work on this course.[Related: Socket Java, python socket UDP]
Pros and Cons of UDP
UDP (User Datagram Protocol) is a simple and fast network protocol that is commonly used for real-time applications such as video conferencing, online gaming, and streaming multimedia content. However, it also has some drawbacks that should be considered.
Pros:
- Speed: UDP is faster than TCP because it doesn't have the overhead of error checking and retransmission of lost packets.
- Low latency: UDP is a connectionless protocol, which means that it doesn't establish a dedicated connection before transmitting data. This results in lower latency and faster response times.
- Simplicity: UDP is a simple protocol that is easy to implement and maintain.
Cons:
- Unreliable: UDP is an unreliable protocol because it doesn't guarantee the delivery of packets. This means that some packets may be lost or arrive out of order, which can affect the quality of the application.
- Security: UDP doesn't provide any built-in security features, which means that it is vulnerable to attacks such as packet spoofing and tampering.
- Congestion: UDP doesn't have any congestion control mechanisms, which means that it could potentially overload a network with too much traffic.