TCP/IP Socket Programming in C# .Net For Coders & Students
4.3 (249 ratings)
Instead of using a simple lifetime average, Udemy calculates a course's star rating by considering a number of different factors such as the number of ratings, the age of ratings, and the likelihood of fraudulent ratings.
5,727 students enrolled
Wishlisted Wishlist

Please confirm that you want to add TCP/IP Socket Programming in C# .Net For Coders & Students to your Wishlist.

Add to Wishlist

TCP/IP Socket Programming in C# .Net For Coders & Students

Learn network programming & socket programming quickly, go from novice to expert today!
Best Seller
4.3 (249 ratings)
Instead of using a simple lifetime average, Udemy calculates a course's star rating by considering a number of different factors such as the number of ratings, the age of ratings, and the likelihood of fraudulent ratings.
5,727 students enrolled
Created by Naeem Akram
Last updated 7/2017
English [Auto-generated]
Current price: $10 Original price: $20 Discount: 50% off
30-Day Money-Back Guarantee
  • 4.5 hours on-demand video
  • 19 Supplemental Resources
  • Full lifetime access
  • Access on mobile and TV
  • Certificate of Completion
What Will I Learn?
  • Create enterprise grade TCP/IP socket communication software
  • Develop a sound understanding of how networking applications communicate
  • Network Programming using .Net Framework Namespaces like System.Net and System.Net.Sockets
View Curriculum
  • C# .Net programming language, basic skills
  • Visual Studio 2010, 2012, 2013, 2015 or above will be needed to write code shown in this course
  • A PC which is connected to a network using Ethernet or WiFi

This course helps you to learn socket programming and become a better professional programmer.

Each video lecture is focused on one important aspect about socket programming & network communication. Concise code examples are supplied, and a demo after every couple of lectures will show you practical implementation of the concepts described earlier.

By the end of this course, you will be able to create C# .Net software capable of sending and receiving data over TCP/IP sockets on peer to peer basis in an asynchronous fashion. The course will make you a better programmer

Why take this course?

You should take this course if you're a professional(or student) with some coding experience in the past but lack understanding of how computer networks work on a software level.

You will learn techniques which are useful in real life scenarios commonly faced by programmers.

Section 1 contains very useful information anybody can benefit from, whether they're familiar with C#.Net or not.

Minimum upfront theory

A lot of courses tend to pile up theory ahead of the real code, this course is going take a minimum theory first approach.

You will learn essentials of network programming and start writing code in under 15 minutes.

Use of Windows Forms

From start to the end this course will use Windows Forms, an approach different from many others taking the command line route. This teaching methodology makes the course lot less boring and non-classroom like, practically useful and really suitable for professionals.

Short, sweet, to the point

Yes sir, entire course is designed with the busy professionals in mind and the videos were created to make your online learning experience fruitful and easy.

Asynchronous Sockets, modern real world solution

In traditional socket programming scenarios, (multi) threading is use to create a responsive server or client. I have bypassed that route and shown you how to use asynchronous sockets directly.

Reinforced learning

Each section contains a quiz on the end which is very helpful to ensure that you review and retain important bits of information imparted in relevant course section.

Open Source Project

All source code shown in this course is also made available as a Git repository through GitHub. The Visual Studio 2010 C# solution is out there! Students can create their own branches, and push changes back for community benefit.

Join an active community

Become a part of the programmers community who have already taken this course. Your questions will be answered by the fellow students and the course instructor as well. Really a wonderful place to start learning!

Learn something new

Sockets are considered an advanced topic, a danger zone in programming parlance. Knowing it means you take your trade seriously.


You will also learn how to implement various sanity checks using tryparse and try/catch.

Who is the target audience?
  • Take this course if you have tiniest C# or Java programming experience
  • Network communications is a very interesting topic, if you're looking to study something off-beat go for this course
  • Don't take this course if you have never written code
Curriculum For This Course
67 Lectures
Essential Networking Theory
8 Lectures 18:25

This course is for programming professionals who have some programming experience but never tried network programming

Many courses and books about network & socket programming pile up tonnes of theory before the real code. That's not the way programmers do it. I have tried to take a different approach and we will get started with only the essential theory and jump into code ASAP.

I am a rookie coder, I've been out there for so many years and written a lot of code (C++, C# .Net, Java) until so far. Because of my approach, will be in a sound position to write software capable of sending and receiving data over the network before the end of this course.

Preview 03:20

The Host

A computer network is made up of hosts, which are also called nodes. A host can be a laptop, a smart phone, a router, or anything and everything that is capable of connecting to the TCP/IP network.

Preview 01:25

An Internet Protocol Address is also called IP Address for short. Every host(computer/phone/router etc.) in a computer can be reached by a unique IP Address.

We will use IP addresses conforming to Internet Protocol Specifications version 4 AKA IPv4, a newer version of IP specifications called IPv6 is also available but it is catching up with the widely used IPv4.

An IPv4 address is basicallly a group of four 8 bit numbers. Each number in the group can have a value between 0 to 255.

When printing an IP address the 4 numbers mentioned above are seperated dot character . to make an IP address easily readable.

Preview 01:04

Note: You may watch the video first and take a look at the description later on if you forget something.

We will use command prompt to find the IP address of your computer.

ipconfig /all is the command which will be used for this purpose. You will need to launch the command prompt and type tie command, then press enter key. All information about the IP configuration of your PC will be dumped on the console as a result. It includes the host name and IPv4/IPv6 addresses of your PC along with the MAC address of various network cards.

If you are connected to the network using Wi-Fi search for "Wireless LAN Adapter Wi-Fi" text on command prompt window. The IPv4 address printed under that heading is the IP address of your PC.

If you are using an ethernet cable, the IP address will be shown under Ethernet group.

It is going to be helpful for later usages to dump IP configurations of your PC to a text file. The syntax of IPConfig command is going to be little different, and its shown below

ipconfig /all > ipc.txt

Now you will notice that nothing gets printed to the screen this time. That's because everything is saved into the text file ipc.txt which we mentioned after > character. If you will type the name of the text file, it will be opened in Notepad where you will be able to see all information about IP configuraiton, search it and copy/paste useful bits around.

Preview 03:04

Note: You may watch the video first and take a look at the description later on if you forget something.

In order to understand port numbers we consider that our PC is an apartment building. This apartment building can be reached using a specific street address. In our case it will be an IP address.

The apartment building is further divided into apartment numbers. Every apartment is identified by a unique apartment number.

Just like apartments a computer contains a large but finite number of ports, each identified by a numeric value.

A single port can be used to read/write or send/receive data by only one process at any time.

When we need to send data to a software process running on another computer or even on the same computere we need to know the IP address of the remote peer and the port number being used by the peer software process.

A combination of IP and port is called an EndPoint.

There are total 65536 ports on a computer. Port numbers from 0 to 1023 are reserved for operating system usage. These are also called well-known ports or system ports.

Preview 01:26

Note: You may watch the video first and take a look at the description later on if you forget something.

This lecture explains how a server process and a client process work together using TCP/IP stream sockets.

The client and server are two separate processes which might be running on two different computers, or on the same computer.

The server proess must start first and perform an accept connections operation. It will use a specific IP Address & port number AKA EndPoint for this purpose.

The client process will be started afterwards. In order t connect with a server the client process will need to know the IP address and the port number on which the server is listening for incoming connections.

If an attempt to connect fails, an exception will occur in client process.

Connection attempts can fail for various reasons, common reasons of client/server connectivity failure include

  1. Windows Firewall blocked either the client process or the server process
  2. The IP address supplied a server IP address to the client is incorrect.
  3. The port number supplied to the client process as server port number is wrong
  4. The server process was not started
  5. The server process was started but it crashed

Once a connection is established, both client and server can perform read and write or send and receive operations in order to send and receive data. Remember, a peer(server or client) can perform a write data or send operation only when the other end has already performed a read data or receive operation.

The client and server can receive and send data to each other as long as both are running and a network connection is available.

The client or server might close the connection whenever they want. A client or server may exit for any reason.

If one end goes offline, the other end will receive an exception.

Preview 03:39

This video shows you how to enable Telnet Client Windows utility, telnet will play an instrumental role in section 2 of this lecture.

Telnet is a feature of Windows OS, its disabled on most machines but users might enable it whenever they want.

Preview 01:18

Its a good idea to make sure that the students have clearly understood the concepts presented in the first section.

When going through this quiz students will have to go back to various lectures and search for the right answers, which will help them in the advanced coding lectures from next sections.

Please take this quiz, it will take only few minutes and it will be very helpful going forward.

Test your Networking Essentials knowledge
11 questions
Socket Programming in C# For Beginners
12 Lectures 57:57
  1. The goal of this video is to get started with the server side of a TCP/IP client server arrangement.

  2. We will create a program which would accept an incoming connection on the IP address of the PC on which it is running.

  3. We are going to use port number 23000.

  4. I will show you the steps needed to call the Accept method.

  5. Please be informed, that this part of the course does not demonstrate production grade code.

  6. The purpose of this section is to familiarize you with how sockets work in principal.

  7. The production grade code will be shown in later sections of this course.

  8. This object will provide us a means to receive data from and send data to the client PC which just got connected.

  9. Let’s head over to Visual Studio

  10. You can use an older version of VS.

  11. I am just showing off my cool new software

  12. We are going to create a C# console application to achieve the goal described earlier.

  13. I’m going to create a new Windows Console type application and name it “SocketsServerStarter”.

  14. First thing we need to do is add the namespaces related to sockets in the program, which are



  1. Inside the main method, I’ll create an object of Socket class.

Socket listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  1. The first parameter means that it’s an IPV4 socket. The other two parameters are self describing.

  2. Next thing, I will create an object of IPAddress.

  3. I’ll assign it the value IPAddress.Any

  4. This means that our socket will be listening for incoming connections on any available IP address on this PC. That can be the loopback IP address or the current IP address shown by the IP config command.

  5. Please don’t get confused by this statement, it will be clarified in next video.

  6. Next, let’s define an IPEndPoint, which is a combination of an IP Address and a port number.

  7. IPEndPoint ipep = new IPEndPoint(addr, 23000);

  8. We passed it the IP address we define above and the port number 23000.

  9. After this, we will bind the socket which we created earlier to the IP End Point which we just created.

  10. This way, our socket will know what IP address and port will it use for its operation.

  11. After this we will call the listen method.

  12. listenerSocket.Listen(10);

  13. The parameter tells the system how many clients can wait for a connection at anytime while the system is busy.

  14. In order to make something happen, we need one final step.

  15. That is to call the Accept method on our socket.

  16. listenerSocket.Accept();

  17. Accept is a blocking operation. It is a synchronous operation.

  18. Our program will not move forward until this operation is finished.
Preview 06:54

In this video we run the server side socket program which we wrote last time. We use Telnet Client utility to connect with a server and put a debugger break point to see the effect of our code. 

Preview 05:16

Receive Data on a TCP/IP Socket

In this video I show you how to convert a byte array into an ASCII string. 

Using Encoding.ASCII.GetString to Convert Bytes To String

  1. Windows Firewall is a security component of Windows Operating System.

  2. If it is turned on, it allows only a specific set of application software to use network for communication.

  3. In case of our socket application, if it tries to communicate with an app running on another device over the network, Windows Firewall is going to block it right there. Because it is turned on at my PC.

  4. The firewall works based on user defined rules.

  5. We can tell it using rules what applications to block and what to allow

  6. Let us open Windows Firewall and add rules to allow our sockets application to communicate.

  7. Open Control Panel

  8. Search for “Firewall”

  9. Click the Windows Firewall link

  10. Click “Advanced Settings” link

  11. Click “Inbound rules”

  12. Click “New rule”

  13. Select “Program” radio button and click “Next”

  14. Click “Browse” button

  15. Go to the path of our project debug folder and select “SocketServerStarter”

  16. Click “Next” and select “Allow the connection”

  17. Click “Next”, don’t change anything and click “Next” again

  18. Supply a name here and some description too. Click “Finish”

  19. Now let’s click the “Outbound” item in tree and add a rule here too.

  20. It is possible to send data to this machine from a telnet terminal running on any other machine on the same network.

  21. For example, we can use another PC for this purpose or my Android smartphone.

  22. Let me show you my phone screen.

  23. I have installed this free app on my phone.

  24. Its name is “Telnet Client”. And no this is not a sponsored advertisement!

  25. Here’s their Google Play store listing

  26. I am going to open this app

  27. On my laptop, I will run our sockets application

  28. It will show an “Allow Access” dialog first time. Click the button “Allow Access”.

  29. And I will click the button “Connect”

  30. In here, I need to supply the IP address of my laptop.

  31. The IP address keeps changing because it is assigned by the DHCP in my home router.

  32. Let’s find it quickly.

  33. So the IP address is and in port number I will put 23000

  34. Over here you can see I can simply send anything I like.

  35. This telnet client is different from Windows telnet client in that we can send more than one bytes of data here.

  36. Let’s have a conversation here.

  37. Looks cool

  38. Now I’m going to go to our server window and type Ctrl C to close the application.  

  39. One last thing,

  40. The name of my PC is shows NWING in the IP configurations here.

  41. Instead of looking for the IP address again and again, I can use this piece of information here.

  42. For example. Let’s run the telnet client app on Android again and try connecting to NWING on port 23000.

  43. Here you see, it works like a charm!!!
Demo - Communicate with Android app, configure Windows Firewall

A short quiz to reinforce the learning. 

Introduction to socket programming quiz 1
4 questions

  1. Sending data back to a client is fairly simple

  2. We need the the client socket to do it.

  3. Please note that we will send data back in byte format.

  4. We can simply echo the stuff sent to us by the client.

  5. In that case, we will be able to reuse the byte array buff along with the local variable client.

  6. The will be client.Send(buff);

  7. And let’s put this part of our code in a while loop.

  8. Right above numberOfReceivedBytes I will add a while(true) and an opening bracket.

  9. And right after client.send I will add the closing bracket

  10. Let us clean the byte array buffer so that I can receive fresh data every time.

  11. Array.clear(0, buff.length);

  12. numbereOfReceivedBytes = 0;

  13. One last thing, there has to be some way to end this infinite loop here. Right?

  14. So, right after client.send(buff) I am going to add an if statement.

  15. if(receivedText == “x”) {break;}

  16. And we’re done here.

  17. Let’s take a look at the change we made again.

  18. In the next video I’ll demonstrate it. And after that I will show you how to deal with the firewall.

  19. And how we can send or receive data to and from another device, like my Android smart phone.

  20. Do watch the upcoming videos, they’ll be really juicy!

Send Data on a TCP/IP Socket

"Nothing is more fun than watching your own code run." Of course this is the height of my poetic skills. 

In this video we will run our server side script and see how it is going to rock and roll by by echoing data back to the client. 

Demo - Send and Receive Data on TCP/IP Sockets

  1. Working with sockets on the client side is fairly similar to to the stuff we have seen in the server side example.

  2. Let me tell you some of those before we start cranking out code. [change slide]

  3. One major difference is that the client sockets don’t do the bind/listen/accept method calls.

  4. Instead, the client sockets perform a connect method call.

  5. In case of TCP/IP, the client socket must know the IP address and port number on which it is supposed to connect.

  6. In case of UDP sockets, there are some other possibilities, but that’s not the subject of this course.

  7. If the client and server are running on the same machine, we can use the loopback IP address to make our lives easier.

  8. I’ve done socket programming on Android too, that means I can teach that too if people are interesting.

  9. I’d be curious to know if you would like to see an Android example too

  10. Anyways, I digress. I’m Sorry :)

  11. Let’s open Visual Studio and create a new console application.

  12. I’ll call our application SocketClientStarter

  13. Inside the code, the first thing I’ll do is add namespaces needed for socket programming

  14. Using

  15. Using

  16. Inside the main method, I’ll define a socket client variable

  17. Socket client =

  18. New socket(

  19. I’ll use the constructor with three parameters

  20. AddressFamily.InterNetwork is for IPV4

  21. SocketType.Stream is for streaming socket

  22. ProtocolType.Tcp is for TCP sockets

  23. We’re going to need the IP Address of our server, let’s define it here and assign it a null for now.

  24. Ipaddrserver = null;

  25. On the next line, let’s define a try/catch block to handle failure scenarios.

  26. catch(Exception excp)

  27.            {

  28.                Console.WriteLine(excp.ToString());

  29.            }

  30. Inside the try block I’ll define a new string and call it strServerIPInput and assign it the value input by user from console.

  31. Let’s give our users a clue about what they’re supposed to do here one line above.

  32. Console.WriteLine("*** Welcome to Socket Client Starter Example by Naeem Akram Malik ***");

  33. Console.WriteLine("Please Type a Valid Server IP Address and Press Enter: ");

  34. Also define a string to take port number input from user.

  35. string strPortInput = Console.ReadLine();

  36. And some help for users

  37. Console.WriteLine("Please Type a Valid Server Port Number(Integer Only, max 65535) and Press Enter: ");

  38. And an int to store the port number int after parsing it.

  39. Now let’s parse the string given by the user into an IP Address.

  40. IPAddress.TryParse(strServerIPInput, out ipaddrserver);

  41. Add an if condition here in case of bad user input.

  42.    if(!IPAddress.TryParse(strServerIPInput.Trim(), out ipaddrserver))

  43.                {

  44.                    Console.WriteLine("Invalid server IP supplied.");

  45.                    return;

  46.                }

  47. We’ll do the same for the port number too.

  48.                if(!int.TryParse(strPortInput.Trim(), out nPortInput))

  49.                {

  50.                    Console.WriteLine("Invalid port number supplied, return.");

  51.                }

  52. The tryparse functions will return false if they fail to parse the supplied strings according to their type specifications.

  53. We also know that a valid port number has to bee greather than zero and smaller than 65535. So, let’s add an if condition to handle that too.

  54. if(nPortInput <= 0 || nPortInput > 65535)

  55.                {

  56.                    Console.WriteLine("Port number must be between 0 and 65535.");

  57.                    return;

  58.                }

  59. Let’s show the stuff on screen too

  60. System.Console.WriteLine(string.Format("IPAddress: {0} - Port: {1}", ipaddrserver.ToString(), nPortInput));

  61. Next, we’ll call the client socket connect method.

  62. client.connect(

  63. We can supply it a new IPEnd point, or use a constructor which takes IP Address and Port directly.

  64. Let’s use the second one:

  65. And supply IP Address & Port

  66. client.Connect(ipaddrserver, nPortInput);

  67. Console.Writeline(“Connected to server.”);

  68. Add a console.ReadKey() on next line.

  69. Please note that this is a blocking call and it will fail after a timeout period if the server is not running.

  70. Let’s try to run it right away without running the server first.

  71. I’ll press control F5

  72. Input IP Address .

  73. Input port number 23000

  74. It fails after a brief pause

  75. An exception is thrown on line number 47, that’s where we try to connect with server.

  76. So now let’s go to our server project and start the server first.

  77. So here you see,we’re connected to the server.

  78. No data will be sent/received right now.

  79. We’ll need to add some send/receive logic to our client program to do that.

  80. Now let’s close the server and go.

  81. You are going to learn just that in the next video, do watch the next video.
Introduction to Client Side TCP/IP Socket Programming

Writing some safe code to input server IP and port. Show use of IPAddress.TryParse and int.TryParse. 

In the end we perform an Connect method call and see how it works with the Server which we have written so far in this course. 

Also show you the poser of Ctrl + . to import missing namespaces into the solution. 

Client Side Socket Programming Project Setup, using Methods Connect and TryParse

How to perform send and receive operations on client side sockets. 

Send & Receive Calls On Client Side TCP/IP Socket

Run the final version of code produced in this section and see how it goes. Make minor changes in the client and server to prevent the applications from crashing. 

Demo - Run TCP/IP Client & Server together, Make Improvements To Server

Summary of the things which we learned in this section. 

TCP/IP Sockets On Server Side

§How to setup a server socket(Bind and Listen)

§The IPAddress.Any constant

§Accept a connection on the server

§Using telnet client utility

§How to Receive and Send data

§Encoding.ASCII to convert byte[] to string

§Clearing the byte array

§Setup Windows Firewall allow

connecting to my phone

TCP/IP Sockets On Client Side

§Why we need to know server IP & port

§Parsing an IP Address safely

§How to connect to a server

§How to Receive and Send data

§Encoding.ASCII to convert string to byte array

§How to shutdown/close/dispose a socket

§Using try/catch to prevent crashes

Did do it wrong?

§I’m going too fast?

§Did I miss something, just let me know

§Feel free to ask questions in Q&A section

§Source code in lecture downloads area

§Also available on GitHub

§I would love to add more videos here

Section Summary
TCP/IP Server Asynchronous Socket Programming With async & await Keywords in C#
12 Lectures 55:00
  1. We are going to get into some exciting production grade stuff in this section.

  2. First of all I will show you how to create non-blocking socket applications using async and await keywords. We’ll start on the server side.

  3. The async/await keywords and relevant methods were introduced in .Net Framework 4.5. So you need a version of visual studio which supports it.

  4. Secondly, we will move on from raw sockets and start using helper classes.

  5. For example, instead of using a socket object to accept incoming connections, I am going to show you how to use a TCPListener.

  6. And instead of using a Socket class object to represent the client, I am going to use TCPClient class object.  

  7. I am also going to show you how to use StreamReader and StreamWriter with network streams.

  8. Yet another wonderful thing is that we’ll create a class library now onwards in this course.

  9. This approach will make the end result of taking this course much more useful my for students.

Section Intro: Asynchronous socket programming with async and await in C# .Net

Example: Disadvantage of synchronous I/O

  1. Let us create a new WinForms Project.

  2. I’ll pick Visual C# => Windows Classic Desktop => Windows Forms App(.Net Framework)

  3. I’ll call it, UdemyAsyncSocketServer

  4. Let’s add a new class library to house the logic of our sockets stuff

  5. Right click the solution in solution explorer and select Add => New Project.

  6. I’ll select Visual C# => Windows Classic Desktop => Class Library(.Net Framework)

  7. I’ll name the library “LahoreSocketAsync”

  8. Lahore is the wonderful city where I live

  9. Click the Class1.cs file and press F2 to rename it to “LahoreSocket.cs”

  10. Click “Yes” when VS asks you if you want to rename the auto generated class too.

  11. First of all, we need to supply an IP address and a port number when a server needs to listen for incoming connections.

  12. Let’s define those in our class.

  13.        IPAddress mIP;

  14.        int mPort;

  15. Click IPAddress and press Ctrl+.

  16. Click “Using System.Net”

  17. Next, let’s define our first method

  18. I’ll call it

  19. public void StartListeningForIncomingConnection(IPAddress ipaddr = null, int port = 23000)

  20. This method will allow the caller to specify an IP Address and a port.

  21. Default values of these parameters are in place for convenience.

  22. Now I need you to pay attention, just in case you’re doing something else alongside watching the videos.

  23. I do it all the time.

  24. We need to add the keyword async before the return type of our method.

  25. This is mandatory if we want to make an async call inside the body of this method.

  26. We are going to use an asynchronous method of a TCP/IP helper class inside this method.

  27. Inside the method, let’s add some code to see if parameters supplied are ok or not.

  28.            if(ipaddr == null)

  29.            {

  30.                ipaddr = IPAddress.Any;

  31.            }

  32.            if(port <= 0)

  33.            {

  34.                port = 23000;

  35.            }

  36.            mIP = ipaddr;

  37.            mPort = port;

  1. Let’s print the final values to the debug output

  2.            System.Diagnostics.Debug.WriteLine(string.Format("IP Address: {0} - Port: {1}", mIP.ToString(), mPort));

  3. Now let’s introduce a variable of type TCPListener.

  4. TCPListener is a .Net framework helper class which makes TCP/IP programming on the server side easier.

  5. mTCPListener = new TcpListener(mIP, mPort);

  6. The system is showing us some squiggles, let’s fix them.

  7. Click TcpLiseneter constructor and press Ctrl+.

  8. Select appropriate socket namespace to add.

  9. Click mTCPListener and press Ctrl+.

  10. Click “Generate field in LahoreServer” option

  11. Now let’s call the start method of our TCPListener.

  12. mListener.Start();

  13. Next, we’ll make the async call

  14. mListener.AcceptTcpClientAsync();

  15. If we hover the mouse on the method, we’ll be able to see more details about it.

  16. The usage section below says we need to put the async keyword behind the method call.

  17. If we take a look at the definition of our method, it also shows a green squigly complaining that we need to await this method.

  18. Let’s introduce the await keyword here, right before the accept call.

  19. Now put the return value in a variable too

  20. var returnedByAccept =

  21. Let’s write some information to the debug console too

  22. I’ll put a breakpoint after the acceptTcpClientAsync as well.

  23. We are going to use the value returned by this method in an upcoming video.

  24. The important point you need to understand is that when the .Net Framework will see the await keyword inside a method which has got async in its definition, it will generate some code behind the scene to make sure things happen in an async manner.

  25. Once the asyc operation is finished, your code will resume execution beyond this point.

  26. Now I’ll go back to my Forms project and add a reference of LahoreSocketAsync.

  27. I’ll go to the Form design view and add a button, I will name it btnStartServer

  28. Double click the button

  29. Go to the top and add a using statement to bring in LahoreSocketAsync

  30. Inside the form class, I’ll create a reference of LahoreServer

  31. LahoreServer mServer;

  32. We’ll instantiate this member variable in form constructor

  33. mServer = new LahoreServer();

  34. Now let’s go back to button click method and start accepting incoming connection request

  35. mServer.StartListeningForIncomingConnection();

  36. Let’s run the code in next video and see the affects of the work we’ve done so far.

Accepting a TCPClient Connection Asynchronously

Demonstration usage of AcceptTcpClientAsync method call to listen for incoming connection requests for non blocking I/O without spinning extra threads in your code. 

Demo: Accept TCPClient Asynchronously

Continuously Accept New Client Connections & Exception Handling in async Method

  1. In order to perform async read operation in method TakeCareOfTCPClient, we need to make it async.

  2. Let’s add the keyword async to the method definition

  3. Inside the method, I’ll define a variable of type NetworkStream and assign it null for now.

  4. NetworkStream stream = null;

  5. I’ll also add a variable of StreamReader type too.

  6. Every TCP/IP stream socket has got an I/O stream attached to it.

  7. Just like the stream available in case of console I/O or file I/O.

  8. We will use the StreamReader to read data from the network stream associated with the TcpClient passed into this method as a parameter.

  9. After that let’s create a try catch block

  10. try

  11.            {

  12. }

  13.            catch(Exception excp)

  14.            {

  15.                System.Diagnostics.Debug.WriteLine(excp.ToString());

  16.            }

  17. Inside the try block, I’ll assign the network stream object a value.

  18. stream = client.GetStream();

  19. I’ll assign the stream reader object a value based on the network stream

  20. reader = new StreamReader(stream);

  21. In order to read data sent from the client through stread reader, we’ll define an array of char

  22. char[] buff = new char[64];

  23. Now we’ll create a while loop

  24. while (keeprunning)

  25. {


  27. }

  28. Let’s write info on debug that we’re ready to read

  29. Debug.WriteLine("*** Ready to read");

  30. After this, we’ll call an async method on stream reader.

  31. We will start with the await keyword

  32. await

  33. reader.ReadAsync(buff, 0, buff.Length);

  34. If we hover the mouse on the call to ReadAsync, we can see that it returns a Task<int> and the usage tells us we can store return value in int.

  35. Let’s define a variable and store the values here.

  36. We’ll also print the number of received bytes to the screen

  37. System.Diagnostics.Debug.WriteLine("Returned: " + nRet);

  38. On the next line, we’ll see if the return value is zero.

  39. When this method returns zero, it means the socket connection has been closed.

  40. In this case, we’ll print a debug log and break the loop.

  41.                    if (nRet == 0)

  42.                    {

  43.                        System.Diagnostics.Debug.WriteLine("Socket disconnected");

  44.                        break;

  45.                    }

  46. In case you are wondering “wait, why the Debug.Writeline?”

  47. Rest assured, we’ll take good care of these messages later in this course.

  48. Next, we’ll convert the received character array into a string

  49. string receivedText = new string(buff);

  50. And print it to the debug console

  51. System.Diagnostics.Debug.WriteLine("*** RECEIVED: " + receivedText);

  52. Before we could start the next read operation, we also need to clear the byte array buffer which we use for receiving data.

  53. Array.Clear(buff, 0, 64);

  54. Now build the solution and make sure it compiles

  55. That’s it, in the next video we’ll run our server application with the client application which we created in the last section.

Reading Data Sent from Client on NetworkStream with StreamReader

Read data from a network stream in C# .Net using asynchronous StreamReader method calls. 

Demo: Read Data On Network Stream and Endless Accept

How to Handle Multiple Network Clients on Server

Demo: Send Data to Multiple Network Clients from List at Once, SendAll Method

How to stop the server and disconnect the client sockets properly

  1. In order to stop the server properly, we’ll need to do two things.

  2. First, stop the TCPListener from accepting new incoming connections.

  3. And second, disconnect all connected clients.

  4. We’ll add a method StopServer to our library to do this.

  5. In this video, I’m going to show you how to do these steps.

  6. Let’s head over to the visual studio

  1. I’ve opened the socket server project

  2. First, I’ll add a button on the Form. I’ll name it btnStopServer and set text to Stop Server.(do form resize and button addition faster).

  3. Double click the button

  4. Inside event handler, I’ll use the object mServer to call a method which does not exist yet.

  5. I’ll say mServer.StopServer()

  6. Now I’ll press Ctrl+. to generate the method and press F12 to go inside of it.

  7. First thing, Let’s add a try catch block.

  8. Inside the try/catch set KeepRunning to false.

  9. Next, if(mTcpListeners != null){}

  10. mTcpListener.Stop();

  11. By doing this, we’ve stopped the listener from accepting new connections.

  12. But, we still have the socket connections open which mean we can still receive/send data.

  13. Let’s go through the list of connected clients and close them one by one. We’ll also remove them from the list.

  14. foreach(TcpClient c in mClients)

  15.            {

  16.                c.Close();

  17.            }

  18. After the loop, we’ll clear the list

  19. mClients.Clear();

  20. We can call this method on the Form OnClosing event too.

  21. I’ll go to the form designer view and open Properties pane.

  22. Click “Events” thunderbolt

  23. That’s it, we’re done. We’ll be able to start and stop our server any time we want after this implemenation.

  24. Let’s run it in the next video.

How to Stop Listening for New Connections and Disconnect Client Sockets Properly

Demo: Stop TcpListener and Close client sockets

  1. I will start our server program and click button “Accept Incoming Connections”

  2. Launch a few clients by pressing Windows + R and supplying the telnet command.

  3. You can see we’re sending data back & forth.

  4. Now if I go ahead and click button Stop Server

  5. You will see that the telnets will close(will have to click the telnet windows)

  6. I can go back and start the server again by clicking the button “Accept Incoming Connections”

  7. And launch a few telnets once again

  8. If I type text on these telnet terminals, you’ll see it reaches across to the server.

  9. And, if I try to send text to all clients, that too is going to work fine. (Click button Send All on server)

  10. This means, that starting and stopping multiple times does not have a bad affect of our server.

  11. Now let’s see what happens if I have stopped the server.

  12. I’ll click the button “Stop Server” once again.

  13. And try to connect a Telnet client to it.

  14. You see, the telnet can’t find our server.

  15. Why? Because we called the TcpListener.Stop method when we click the button “Stop Server”.

  16. That’s the reason the server does not listen for new incoming connections.

  17. Now you know how to stop the tcp listener from accepting new connections and how to do away with the tcp client objects too.

Demo: TcpListener.Stop and TcpClient.Close Calls to Stop Server

Section Summary: Asynchronous Socket Programming

  1. Let’s quickly recap the useful things we learned in this section.

  2. In this section, we got started using async and await keywords along with some special async socket I/O methods.

  3. We learned how to accept incomi ng connections using socket helper class TcpListener.

  4. We used the method AcceptTcpClientAsync() to accept connections in a non blocking way

  5. After that, we saw how we can continuously listen for incoming connections and how to handle exceptions in the async method of our class library.

  6. Without impeding the operations.

  7. We also came to know about the TCPClient helper class, which makes client side socket programming easier.

  8. Then we went on to use the ReadAsync method of the network I/O stream using an object of StreamReader.

  9. Not to mention that this too is an asynchronous method, which doesn’t block our application.

  10. Afterwards, we wrote the logic to maintain a list of clients connected to our server.

  11. This list was used to send data to all connected clients using WriteAsync method of NetworkStream attached to the instance of the socket which is attached to our TcpClient.

  12. In the end, I showed you how to stop the server properly by calling the Stop method on the TcpListener and how to disconnect a socket by calling Close method on a TcpClient.

  13. I hope you would’ve found this section useful. Feel free to ask questions in Q&A section.

  14. You can clone or fork the public repositories of this library on GitHub. It’s all yours to modify, improve, and play.

  15. If you think this course has been useful, this course has added value to your life, please leave a positive rating and review.

  16. Next section, we’ll create the client application using async calls.

Section Summary: TCP/IP Server Side Asynchronous Socket Programming in C# .Net
Async Client Side Socket Programming
10 Lectures 29:44
  1. Hi, in this video we’re going to setup a project to create the async client side software of a TCP/IP client server arrangement.

  2. We’re going to add another class to our library LahoreSocketAsync for this purpose.

  3. This work will be done in a console application, to take down two birds with one stone.

  4. We’ll create a new C# console application solution and project and then add the existing library to it.

  5. The server and client solutions refer to the same library, but I’ve kept the solutions separate intentionally.

  6. This is going to make our life easier when we’ll be debugging.

  7. Let’s get started(<do> create project here)

  8. I’ll add a the existing socket library project to this solution

  9. In the solution explorer, I’ll right click the solution and select Add => Existing Project

  10. I’ll go to UdemyAsyncSocketServer folder and go to LahoreAsyncSocket folder

  11. Add LahoreSocketAsync project

  12. Right click LahoreSocketAsync project and select Add => New Item

  13. Select “Class” And name it “LahoreSocketClient”

  14. All right, we’re cool here. In the next video, we’ll some logic to connect with a server and start reading data.

Client side async socket project setup

  1. In this video, we’re going to call the async method TcpClient.ConnectAsync to connect with the server.

  2. We will also add the member variables needed to represent the server IP Address, server port number, and the TcpClient object.

  3. In order to make the class available publicly, we will add public access specifier to our client class name too.

  4. I’ve opened the socket client library project.

  5. First thing, I’ll add member variables to class LahoreSocketClientAsync to store server IP and port.

  6. IPAddress mServerIPAddress;

  7. Click red squigly, click light bulb, and click “Add System.Net;

  8. int mServerPort;

  9. We’re going to use a TcpClient helper class to connect with the server. Let’s declare it at the class level.

  10. TcpClient mClient;

  11. Add relevant namespace using System.Net.Sockets;

  12. I want to declare class constructor to set default values of these members here.

  13. Ctor double tab

mClient = null;

mServerPort = -1;

mServerIPAddress = null;

  1. Now Let’s create getters for these members.

  1. The setters will be a little different. I want to return false if the user supplies an invalid IPAddress or Port values.

  2. Let me define a new method here

  3. Let’s create a similar method for the port number too.

  4. public bool SetPortNumber(string _ServerPort)

       Now comes the heart of this video, the async method ConnectToServer.

  1. public async Task ConnectToServer()



  1. This method is declared to be async because we’re going to make an async method call inside of it.

  2. The return type Task is essentially equivalent to void.

  3. The MSDN says we should use async Task instead of async void for async methods. Going into the details will be beyond the scope of this course.

  4. Now let’s add the method

  5.       public async Task ConnectToServer()




  1. If mClient is equals to null, we’ll assign it a new instance.

  2.   if(mClient == null)


               mClient = new TcpClient();


  1. We’ll use the constructor without parameters.

  2. Let’s add a try/catch block for safety sake

  3. And then, we

  4. ’ll call the method mClient.ConnectAsync

  5. We’ll supply this method with the IPAddress of the server and the port number.

  6. Await mClient.ConnectAsync(mServerIPAddress, mServerPort);

  7. Console.WriteLine(string.Format("Connected to server IP/Port: {0} / {1}", mServerIPAddress, mServerPort));

  8. This is it, we’re in good shape. We’ll add the logic for reading data from the socket network stream in the next video. We’ll also call these the newly added in our console application and have a demo afterwards. See you in the next video!

Async Client Socket Programming

Creating a console application and adding library reference

In this video, we’re going to write code to read data sent down from the server to our client.

2.    The receive operation is going to be exactly the same like we saw in the server side video previously

3.    I’ll go inside the LahoreSocketClient class dot  c s file.

4.    In the ConnectToServer method, I’ll go to the point after  the method call

5.    await mClient.ConnectAsync(mServerIPAddress, mServerPort);

6.    We need to add three local variables here

i)   A streamreader to read data off the network stream of our TcpClient object

ii) A char array to store the data sent by the server

iii)   And an int to store the number of characters read in

7.    Let’s declare the variables

  9.    You can see that we’ve called the constructor of StreamReader and passed it the result of mClient.GetStream() method.

10.  This method is going to return the network stream associated to the instance of our  TcpClient.

11.  A network stream is attached to every socket and every TcpClient to perform I/O operations.

12.  I’ll click the StreamReader and press Ctrl+. And click using System.IO; to bring in the relevant namespace.

13.  Now add an infinite while loop which will end only when the connection is broken from the server.

17.  Inside this loop, I’ll call the ReadAsync method of our stream reader.

18.  await clientStreamReader.ReadAsync(buff, 0, buff.Length);

19.  This method is going to return the data sent by the server in the first parameter, which is the char array buff.

20.  We’ve told the method that it can start putting data in the output buffer starting from zero and ending at the length of buffer.

21.  Let’s put the return value in the readByteCount variable.  

23.  If the read byte count is ever less than equal to zero, that means the connection with server has been broken.

24.  We’ll put this fact in code

We will need to close the client before moving forward.

25. And now write the result to the console.

26.  Console.WriteLine(string.Format("Received bytes: {0} - Message: {1}", readByteCount, new string(buff)));

27.  Before we start reading data again, we need to clean the buffer.

28.  Array.Clear(buff, 0, buff.Length);

29.  This is it, we’re all set for receiving data too.

30.  We’ll have a demo in the next video!

Reading data from TcpClient socket network stream

Demo: Client side TCP/IP socket programming

1.       Sending data to the server is again, a fairly simple task.

Just like everything else in this course.

2.       We will use an object of stream writer to write data on the socket connected to our instance of TcpClient.

3.       Needless to say, we’ll do it in a non-blocking way and add an async method to our client class.  

Let’s open the client project in visual studio.

4.       We’ll head over to the main method in the console application.

5.       Inside the do while loop, we can send the input data to the server if user input is not equal to <EXIT>

      if(strInputUser.Trim() != "<EXIT>")




6.       Inside the if condition Let’s call an arbitrary send method on the client object.

7.       We’ll define this method later on.28-Read data on stream reader

8.       client.SendToServer(strInputUser);

9.       Now I’ll click the method call SendToServer and press Ctrl+.

10.   And select Generate method

11.   Next, I’ll press F12 and go to the method definition

12.   The default implementation is throwing NotImplementedException, let’s remove it

13.   We also need to add the keyword async to the method signature to make it non blocking

14.   Let’s do it

15.   And as you remember I told your earlier, we must never put async void in a method signature.

16.   Instead, we should use async Task

17.   Inside of this method we can simply check if the mClient is not null and if it’s connected.

        if(mClient != null)







18.   I also don’t want to do anything when the user has supplied a null or empty parameter. Let’s put this in code too.

19.   We’ll do it at the top section of the method.


if (string.IsNullOrEmpty(strInputUser))


            Console.WriteLine("Empty string supplied to send.");



21.   Now let’s create an instance of a stream writer to send data.

  StreamWriter clientStreamWriter = new StreamWriter(mClient.GetStream());

  clientStreamWriter.AutoFlush = true;

24.   Auto flush is an important property.

25.   This means that as soon as one write operation is finished, the data should be flushed over to the other end of stream.

26.   And that is just it!

27.   Let’s have a short demo in the next video.

Writing data on the a client socket

Demonstration, writing data on TcpClient network stream.

Demo: Write data on TcpClient network stream

  1. Let us write a method to close and disconnect the TcpClient.
  2. We’ll first go to the program.cs file.
  3. Inside the while loop, Right after the if input is not equals to null, I’ll add an else if condition.
  4. Inside this if condition, I will call a method which we will define in a moment.
  5. I’ll click the Disconnect method and the bulb and generate the method.
  6. Then, I’ll press F12 to go to the method body.
  7. Remove the default code.
  8. And I’ll add some new logic in here.
  9. That’s all for this video, let’s have a demo in the next one.
  10. I’ll run the server first and start listening for incomings
  11. Then I will run our client program.
  12. I’ll supply it the IP address & port number
  13. Then I will type <EXIT> command.
  14. The client will close peacefully.
  15. I can see that I can start the client again and exchange data with the server.
  16. Closing the client does not cause any problem.
  17. We can see that the server logs contain no exceptions.
  18. Let’s run the client one more time.
  19. This time, I’ll close it by clicking cross button directly.
  20. You’ll see that the server is handling an exception in this case.
  21. So, always be a responsible citizen and close your sockets properly.

else if(strInputUser.Trim().Equals("<EXIT>"))




if(mClient != null)


                if (mClient.Connected)





Close Connection on TCPClient

Demo of how to close a TCP/IP client side connection properly. 

Demo: Closing connection on TcpClient

§Setup a new solution for client side network programming

§Added a new class to the library

§TcpClient.ConnectAsync method call

§Read data with StreamReader.ReadAsync method call

§Write data with StreamWriter.WriteAsync method call

§Close a connection with TcpClient.Close method call

Section Summary: Async client socket programming
Using Publisher Subscriber Model To Add Events
4 Lectures 25:24
  1. We will publish events that conform to .Net Framework Guidelines as specified on Microsoft’s website.
  2. You can see the page on screen.
  3. We will define events based on generic EventHandler delegate which is defined in .Net Framework.
  4. The website is shown on screen
  5. The event objects which we will define are going to hold one or more references to method names in the subscriber code.
  6. Delegate definition is quite simple.
  7. The first parameter will contain a reference to the object from which the event was raised
  8. The second parameter will contain an object of a class derived from EventArgs.
  9. We will create a special class for this purpose.
  10. The EventArgs derived object will contain event specific information.
  11. Let’s open the LahoreSocketAsync project in the UdemyAsyncSocketServer solution
  12. First of all, I will define a custom class derived from EventArgs
  13. Right click the “solution”, go to “Add”, Select “New Item”, and select “Code”, “Code File”Name it “CustomEventArgs.CS”.pri
  14. Now copy over the namespaces stuff.
  15. To add a new class, I’ll type class and press double tab.
  16. I’ll rename the class and make it derive from EventArgs
  17. I want this event arguments to contain the IP address of currently connected client
  18. So, I’ll add a new private string here.
  19. And a getter for this string.
  20. Let’s add a parameterized constructor to this class too.
  21. The first parameter will be a string representing the EndPoint of newly connected client.
  22. Now let’s go to the LahoreSocketServer class.
  23. In here, we’ll add a public member EventHandler of ClientConnectedEventArgsIn order to raise this event, we’ll define a new method too.
  24. The method is defined as protected virtual such that derived classes can override event invocation behavior
  25. Inside the OnRaise method, we will create a temporary copy of the event handler object to avoid race conditions.
  26. EventHandler<ClientConnectedEventArgs> handler = RaiseClientConnectedEvent;
  27. Then a sanity checks to make sure handler is not null.
  28. the call to handler
  29. handler(this, e);
  30. We are going to call the OnRaise method right after a new client has connected.
  31. For this purpose We’ll go to the method StartListeningForIncomingConnection
  32. Right after the debug line we can see a method TakeCareOfTCPClient
  33. We’ll raise event after this method call
  34. Let’s prepare the event arguments first of all, this object will contain important information about the event being raised.
  35. We’ll new it
  36. And then we’ll call the OnRaise method
  37. We could’ve done this in one line, but I prefer clarity on cleverness.
  38. Let’s head over to the subscriber side of the application and add some code to configure & consume this event.
  39. I’ll open the UdemyAsyncSocketServer.
  40. Right click the Form1.cs and select View Code.
  41. Let’s go to the bottom of the file and add a new event handler method here.
  42. Once we’re done, this method will be the voice of our library.
  43. The library will be able to invoke this method when a new client will connect.
  44. Utilization of the information will be totally up to the consumer form application.
  45. We need to define a method whose first parameter is an object and second parameter is ClientConnectedEventArgs.
  46. So that, it conforms to the event defined by the server library(?? Can we show some reference material here ??)
  47. Before we fill into the body of this method, let’s add a multi line text box to the form. I’ll name it txtConsole. <DO THIS QUICKLY>
  48. Back in the HandleClientConnected, I will add the information to the txtConsole.
  49. Now, the last and most important step is to hook the subscriber method up to the publisher method
  50. To do this, we’ll go to the point where we new up the server object.
  51. In case you’re not familiar with event handlers, we’ll use the plus equals to operator to assign the subscriber method to the publisher hook.
  52. mServer.RaiseClientConnectedEvent += HandleClientConnected;
  53. Instead of having a demo in a separate video as we usually do, let’s run the server right away and see how it goes.
  54. I’ll start the server and click “AcceptIncomingConnection” button.
  55. Then I’ll press Windows + R and supply telnet command several times
  56.  If we take a look at the server form now, we can see that it is showing a message about client connected.
  57. I have an assignment for you
  58. The assignment is you have to create a similar event system when a client gets disconnected.
  59. You’ll create a class derived from eventargs,
  60. On the publisher side, a generic member to store the evet handler, a method to fire the event handler, and call it in the server appropriately on one or more places,
  61. On the subscriber side
  62. You’ll write add an event handler
  63. And plug it in to the publisher’s hook. See you in the next video! 

Introduction to pub/sub model and events

Adding a ClientConnected event to the publisher library and handling it in the subscriber side as well. 

Adding a ClientConnected event to the server

Time to publish another event in our socket library. This time we'll add a TextReceived event on the server and display the information in a Forms text box.

Adding a TextReceived event on the server

How to publish a TextReceived event in client side classes. 

Publishing event TextReceived on client
Deprecated Section: Creating a TCP/IP socket server
9 Lectures 33:20

In this lecture we are going to setup a project in Visual Studio which will be used throughout the course. Contrary to most tutorials, you will notice that I am using a Forms application. It will give you a feel that you are building something "real" and it will also make things easier overall.

Important namespaces for socket and network programming are given below:



Preview 04:07

System.Net.TCPListener is used to listen for incoming connection requests. We will initialize the TCPListener in an onClick event of a button, it will need a valid IP address and port which will be passed in through the form fields.

This lecture will also show you how to implement some sanity checks to make sure that correct values are supplied. We will use the method IPAddress.TryParse to ensure correctness of IP address, and int.TryParse for port number.

Preparing a TCPListener

We will call the asynchronous method beginAcceptTcpClient of TcpListener class. A method from our code will be passed as a parameter, when a new client will get connected to your server process this specific delegate method from your code will be called by the system.

This video will show you how to define the callback. You will see an example of asynchronous programming, which will let your program to run smoothly in non-blocking fashion while the system is still listening for incoming connection requests over TCP/IP socket.

Listening for incoming connection requests

- Important: Always remember to turn Windows Firewall off, or allow your applications through it by adding an exception to the firewall settings. Otherwise the Windows firewall will most probably blog your socket program from sending/receiving data over the network.

This video shows you that you have already got the seeds of a network application in place.

You will run the server code written so far, you will run telnet utility as a client and try to get it connected with your server process.

Preview 02:47

Note: The description is for reference purpose only, you may read it after watching the video.

The two classes given below are very important in our course:

  1. System.Net.Sockets.TcpListener
  2. System.Net.Sockets.TcpClient

We have seen that the server role is wrapped the TcpListener class, and we have used to to accept incoming connection requests.

Similarly, the client role is wrapped in TcpClient class.

These classes encapsulate the sockets, end points, and streams which are needed to communicate over the network.

These classes make our lives easier by hiding a lot of mundane details.

We will use an object of TcpClient to receive data from a peer. An object of TcpClient will be returned by a EndAcceptTcpClient method call inside the onCompleteAcceptTCPClient method.

It is a good practice to use try/catch whenever you can, a lot of trouble and client side embarassment can be saved by a simple try/catch block.

Getting hold of a TCPClient object

Note: The description is for reference purpose, you may read it later on to refresh the things learned in the lecture.

In this video we will put together the plumbing needed to receive data from a socket client.

We will use an async method call BeginRead to read data from the client data stream. We will also define a callback delegate method which will be invoked by the system when some data is received on a client stream.

All data received over the network is in byte form, we will store the received data in a byte array.

The number of bytes received are returned by the EndRead method call.

If the number of bytes received is zero, it means that the other end of the connection is closed.

The method call Encoding.ASCII.Getstring method to convert the received bytes into string which could be printed.

Once the read operation is completed, we clear the buffer and start another read operation so that the client could send more data.

We will run the code in next video and demonstrate that our socket code is working.

Reading data from a TCPClient network stream

This video demonstrates an example of reading data from a TCP/IP socket client. Telnet utility is used for this purpose.

Telnet is a character based interface and as soon as a charater is typed it is sent over to our server application.

In case you have more than once PCs, you can try to run the server application we have created so far on one PC and the telnet utility on another PC.

If we will close the telnet utility first, our server program will show a messagebox to inform the client as well.

Preview 02:00

Note: The description is for reference purpose, you may read it later on to refresh the things learned in the lecture.

The network write or send operation is considerably simple to socket read or receive operation.

We will add a text box and a button which will be used to send data.

Please note that the data is sent in a byte form.

We don't try to send data if the supplied string is null or empty and we use string.IsNullOrEmpty method for this purpose.

We also check if mTCPClient is not equal to null and if the underlying socket represented by TcpClient.Client is connected or not by reading TcpClient.Client.Connected boolean property.

The text is converted into bytes using static method of class Encoding.ASCII which is Encoding.ASCII.GetBytes.

A simple call back method onCompleteWriteToClientSteam method is also defined which only calls the method EndWrite. A try/catch safety net is prsent even in this method.

Writing data to a TCPClient network stream

We will build and run the code which we have written so far.

This video will show you how to exchange data between your server and Telnet client utility.

Your TCP/IP socket server is now capable of handing incoming connection requests and send/receive data to/from a client.

The client and the server can exchange data in this fashion as long as they want and an underlying network is available.

Our server performs the key networking tasks, these are:

  1. Listen for incoming connection requests
  2. Send data to a client
  3. Receive data from a client
Preview 02:38

This quiz is intended to enforce the concepts and tools students have learned during section 2.

Creating a TCP/IP Server
11 questions
Deprecated Section: Creating a TCP/IP socket client
6 Lectures 17:36

Note: The description is for reference purpose, you may read after watching the video.

We will create a form almost identical to the form used in section 2. In this lecture we will add various controls like TextBox, Button, Label to the form.

I will also rename the objects for ease of use and a cleaner code.

Naming controls and objects properly is a very good approach and it makes your code self explanatory in many cases. The approach is certainly not an alternate to adding proper comments to your code, it is a complimentary technique which makes your code even more easily understandable.

Preview 01:34

We will add the namespaces which provide network and socket capabilities to our code. These .Net namespaces are:



An object of TcpClient will be defined as well. We will also add an event handler for btnConnect click event. After this we will add a callback/delegate method that will be called upon end of a connection attempt.

The method TcpClient.BeginConnect allows us to connect with a server process. It will be called in btnConnect_Click event handler method.

Connect to a TCP/IP socket server

The text from a TextBox named "tbPayload" will be sent to a server when the send button will be clicked on our WinForm.

Please note that we must be connected to a server process in order to send data.

An array of byte will be used to hold the bytes equivalent of the string supplied through the Textbox.

ASCII text conversion to byte form is done using GetBytes static method of Encoding.ASCII class.

We will use following method call to send or write the data


A very simple callback delegate method will be written to handle completion of write method as well.

Send data to a TCP/IP socket server

In this video we will dmonstrate the TCP/IP socket client functionality of the code we have written so far in section 3.

Disable Windows Firewall or add an exception so that TcpServer01 and TcpClient01 can use network to transmit and receive data.

We will need the TCPServer01 software that we created in section 1. You can download the exe from the "Downloadable Resources" section of this video or run the project through code written in section 2.

First of all we will run TcpServer and click " supply the IPv4 Address of our PC and port number, we will click "Start Listening" button after these steps.

Once the server is running and listening for incoming connections, we will run our TCPClient project. The IP address and port number of server will be supplied to the client and "Connect" button will be clicked.

Client will be able to send any amount of data it wants to the sever.

The server will not be able to send data back to the client since the client has not implement the TCP/IP network socket stream read operation until so far.

Preview 02:08

In this video I will show you how to implement TCP/IP network socket stream read operation in order to receive data from a TCP/IP client over the network.

The technique to read data on client side is exactly the same as reading data on the server side. Remember we implemented data receive operation in section 2 of this course.

We will define an array of byte and call it mRx as a member variable of our TCPClient01 form class.

The logic of reading data will be added to onCompleteConnect callback method.

The method TcpClient.GetStream().BeginRead will be used to initiate data read operation.

Some commonly used sanity checks and a try/catch safety net is going to be present as usual.

Once a read operation is finished we will start another read operation right away so that the server can keep sending more data to the client.

After going through this lecture we have completed a TCP/IP sockets based server and a client.

The duo can exchange data over the computer network as long as the two want.

We didn't use bare-bone sockets in this course. Instead, I showed you how to use .Net Framework utility classes TcpClient and TcpListener. Using these helper classes makes a developer's life easier and development much faster.

Receiving data from a server

This is a very exciting demo since we are going to see the stuff that we have built so far in action.

First of all let us run the TCPServer01.exe, it is available in downloads section of this lecture.

Once TCPServer is running and listening for incoming connections we will run TCPClient and connect it to our TCP/IP Server.

Data exchange between the TCP/IP network socket client and server will be shown and explained in this video.

Preview 01:55
Deprecated Section: Common Network Programming Topics
6 Lectures 25:23

A loopback address is a special IP address, is most commonly used loopback address.

This video provides an easy explanation of loopback address.

IPv4 addresses from to are reserved as loop-back addresses. It is an implementation detail guarded by various International Engineering Task Force (IETF) standards.

A set of loop back addresses is defined for IPv6 as well but that is not relevant to our course.

A loopback address is used to ease communication and data exchange between a client and a server process if both are running on the same computer.

By using loopback address the client/server don't need to know the exact IP address of their peer and they can communicate seamlessly through the loop-back address.

There is one tricky scenario worth mentioning.

If the client and server are running on same machine but the server is listening for incoming connections on the IPv4 address of the computer instead of the loopback address, the client will not be able to get connected to the server using the loopback address.

The server must be listening on the loopback address if it wants the client to allow to connect with it using loopback address.

Please note that a server running on loopback address is not accessible to other clients on the network.

This video shows you how to use the loopback address to send and receive data between a client and a server.

Preview 03:16

This video lecture shows code for finding an operational IPV4 address of your computer. Please note that this might not be the best method to do the job, someone might have a better technique but that is not the point. We are just trying to understand computer network programming concepts in a quick and practically feasible way in this course.

Finding IPv4 Address using Code

On the server side, it is possible to handle more than one clients at once. Web servers like Apache and Microsoft IIS do it all the time. Traditionally we would start a separate thread manually for this purpose. In our case, we are using asynchronous sockets which give us an advantage. We don't need to start and manage threads manually to handle socket communication or to listen for new requests. That part is handled by the .Net framework on our behalf.

In real world scenarios, you will need to be careful with managing concurrency around shared data though(using semaphores, lock, and monitors).

Handling more than one clients connection requests on server

The most asked for video is finally out. I hope you'll find it useful.

You are going to learn how to maintain a list of currently connected clients and how to send them data and how to receive data.

I have recently create a course title "Windows Service Programming in C# .Net for Coders & Students". I believe it will be useful for most of you. A discount coupon link is given below, grab it before the coupons run out:

Bonus: Maintaining a list of clients to handle multiple clients on your server

In this exciting demo, you are going to see the server capability to handle multiple clients at once. You will also see how to handle client disconnections. Our server is now capable of sending data back to specific client node.

The URL of my new course "Windows Service Programming in C# .Net for coders & students":

Preview 04:51

Listen for incoming connections on "Any" IP Address
1 page
About the Instructor
Naeem Akram
4.3 Average rating
332 Reviews
10,997 Students
2 Courses
Sr. Software Engineer

I am A person with many talents and interests, ranging from gardening to programming and poetry to cooking.

I've been writing computer software code(C++, C# .Net) since 2006, creating awesome Android apps since 2012. I've been working as a freelance software developer since Nov. 2012.

I've extensively worked on network communications, computer telephony integration(CTI) using Microsoft TAPI 2.x and 3.x, and LDAP server programming(Active Directory). Android app development has been my focus as a freelancer, I've created and published several apps for clients and a couple for myself on Google Play store.

I've been sharing my knowledge through my blogs, and I am confident its time share more things that I've experienced with the world in a comprehensive video format.