TCP/IP Socket Programming in C# .Net For Coders & Students
4.4 (220 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,593 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!
Bestselling
4.4 (220 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,593 students enrolled
Created by Naeem Akram
Last updated 7/2017
English
Current price: $10 Original price: $20 Discount: 50% off
30-Day Money-Back Guarantee
Includes:
  • 2.5 hours on-demand video
  • 8 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
Requirements
  • 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
Description

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.

Bonus

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
41 Lectures
02:33:41
+
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
+
New Section - 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

System.Net;

System.Net.Sockets;

  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 127.0.0.1 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 TCP/IP Socket
03:21

  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 192.168.10.5 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
07:54

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
04:15

  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 TCP/IP Socket
03:46

"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
02:28

  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 127.0.0.1 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 System.net

  15. Using System.net.sockets

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

  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
01:48

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
08:30

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

Send & Receive Calls On Client Side TCP/IP Socket
05:01

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
05:30

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
03:14
+
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:

System.Net

System.Net.Sockets

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
03:30

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
03:41

- 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
02:45

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
06:34

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
05:18

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
+
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:

System.Net

System.Net.Sockets

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
03:59

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

TcpClient.GetStream().BeginWrite

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
03:33

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
04:27

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
+
Common Network Programming Topics
6 Lectures 25:23

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

This video provides an easy explanation of loopback address.

IPv4 addresses from 127.0.0.1 to 127.0.0.8 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
06:22

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
01:57

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:

https://www.udemy.com/windows-service-programming/?couponCode=FIVE

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

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":
https://www.udemy.com/windows-service-programming/

Preview 04:51

Listen for incoming connections on "Any" IP Address
1 page
About the Instructor
Naeem Akram
4.4 Average rating
291 Reviews
10,837 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.