Sunteți pe pagina 1din 9

C# Corner Annual Conference 2020 Tickets on Sale Now x

.NET Core 3.0 New Features You Need To Know

Become a member Login


Socket Programming In C# C# Corner
Post Ask Question
Dottys Last updated date Jun 07 2019 648.6k 16 16

Download Free .NET & JAVA Files API


Try Free File Format APIs for Word/Excel/PDF

Sockets in computer networks are used to establish a connection between two or more computers and used to send data from one computer to another. Each
computer in the network is called a node. Sockets use nodes’ IP addresses and a network protocol to create a secure channel of communication and use this channel to
transfer data.
 

 
Socket client and server communication.
 
In socket communication, one node acts as a listener and other node acts as a client. The listener node opens itself upon a pre-established IP address and on a
prede ned protocol and starts listening. Clients who want to send messages to the server start broadcasting messages on the same IP address and same protocol. A
typical socket connection uses the Transmission Control Protocol (TCP) to communicate.
 
In this article, we will see how to create a socket and setup a listener server node that starts listening to any messages coming to it via the prede ned IP and protocol.
We will also see how to create a client application that will send message to the listener server and read it. The sample code is written in C# and .NET Core.
  .NET Core 3.0 New Features You Need To Know
Step 1 - Create a Listener Become a member Login
 
C# Corner
Create a .NET Core Console app and write the following code listed in Listing 1.   Post Ask Question

01. using System;


02. using System.Net;
03. using System.Net.Sockets;
04. using System.Text;
05.
06. // Socket Listener acts as a server and listens to the incoming
07. // messages on the specified port and protocol.
08. public class SocketListener
09. {
10. public static int Main(String[] args)
11. {
12. StartServer();
13. return 0;
14. }
15.
16.
17. public static void StartServer()
18. {
19. // Get Host IP Address that is used to establish a connection
20. // In this case, we get one IP address of localhost that is IP : 127.0.0.1
21. // If a host has multiple addresses, you will get a list of addresses
22. IPHostEntry host = Dns.GetHostEntry("localhost");
23. IPAddress ipAddress = host.AddressList[0];
24. IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
25.
26.
27. try {
28.
29. // Create a Socket that will use Tcp protocol
30. Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
31. // A Socket must be associated with an endpoint using the Bind method
32. listener.Bind(localEndPoint);
33. // Specify how many requests a Socket can listen before it gives Server busy response.
34. // We will listen 10 requests at a time
35. listener.Listen(10);
36.
37. Console.WriteLine("Waiting for a connection...");
38. Socket handler = listener.Accept();
39.
40. // Incoming data from the client.
41. string data = null;
42. byte[] bytes = null;
43.
44. while (true)
45. .NET{Core 3.0 New Features You Need To Know
46. bytes = new byte[1024];
47. int bytesRec = handler.Receive(bytes); Become a member
C# Corner Login
48. data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
49. if (data.IndexOf("<EOF>") > -1) Post Ask Question
50. {
51. break;
52. }
53. }
54.
55. Console.WriteLine("Text received : {0}", data);
56.
57. byte[] msg = Encoding.ASCII.GetBytes(data);
58. handler.Send(msg);
59. handler.Shutdown(SocketShutdown.Both);
60. handler.Close();
61. }
62. catch (Exception e)
63. {
64. Console.WriteLine(e.ToString());
65. }
66.
67. Console.WriteLine("\n Press any key to continue...");
68. Console.ReadKey();
69. }
70. }

Listing 1.
 
The code listed in Listing 1 creates a Socket listener on the local host using TCP protocol and any messages captured from the client, it displays it on the console. The
listener can request 10 clients at a time and the 11th request will give a server busy message.
 
The output will look like Figure 1.
 
.NET Core 3.0 New Features You Need To Know

Become a member
C# Corner Login

Post Ask Question

 
Figure 1.
 
Step 2 - Create a Client 
 
A client application is the one that establishes a connection with a server/listener and send a message. Create another .NET Core console application and write the
following code in Listing 2.
 
The sample code in Listing 2 creates a client application that creates a socket connection with the listener on the given IP and the port, and sends a message. 

01. using System;


02. using System.Net;
03. using System.Net.Sockets;
04. using System.Text;
05.
06. // Client app is the one sending messages to a Server/listener.
07. // Both listener and client can send messages back and forth once a
08. // communication is established.
09. public class SocketClient
10. {
11. public static int Main(String[] args)
12. {
13. StartClient();
14. return 0;
15. }
16.
17.
18. public static void StartClient()
19. {
20. byte[] bytes = new byte[1024];
21.
22. try
23. {
24. // Connect to a Remote server
25. // Get Host IP Address that is used to establish a connection
26. // In this case, we get one IP address of localhost that is IP : 127.0.0.1
27. // If a host has multiple addresses, you will get a list of addresses
28. IPHostEntry host = Dns.GetHostEntry("localhost");
29. IPAddress ipAddress = host.AddressList[0];
30. IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
31.
32. .NET//
Core 3.0 NewaFeatures
Create TCP/IPYousocket.
Need To Know
33. Socket sender = new Socket(ipAddress.AddressFamily,
34. SocketType.Stream, ProtocolType.Tcp); Become a member
C# Corner Login
35.
36. // Connect the socket to the remote endpoint. Catch any errors. Post Ask Question
37. try
38. {
39. // Connect to Remote EndPoint
40. sender.Connect(remoteEP);
41.
42. Console.WriteLine("Socket connected to {0}",
43. sender.RemoteEndPoint.ToString());
44.
45. // Encode the data string into a byte array.
46. byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
47.
48. // Send the data through the socket.
49. int bytesSent = sender.Send(msg);
50.
51. // Receive the response from the remote device.
52. int bytesRec = sender.Receive(bytes);
53. Console.WriteLine("Echoed test = {0}",
54. Encoding.ASCII.GetString(bytes, 0, bytesRec));
55.
56. // Release the socket.
57. sender.Shutdown(SocketShutdown.Both);
58. sender.Close();
59.
60. }
61. catch (ArgumentNullException ane)
62. {
63. Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
64. }
65. catch (SocketException se)
66. {
67. Console.WriteLine("SocketException : {0}", se.ToString());
68. }
69. catch (Exception e)
70. {
71. Console.WriteLine("Unexpected exception : {0}", e.ToString());
72. }
73.
74. }
75. catch (Exception e)
76. {
77. Console.WriteLine(e.ToString());
78. }
79. }
80. }
.NET Core 3.0 New Features You Need To Know
Listing 2. Become a member Login
C# Corner
 
Step 3 - Test and Run Post Ask Question
 
Now build both projects and run both applications from the command line. You will see the message sent by the client is read and displayed by the listener. 
 
Once client runs, you will see the message is sent to the server. See Figure 2 
 

 
Figure 2.
 
Summary
 
In this article, you learned how to use Sockets in C# and .NET Core to create a client and a server to communicate via the TCP/IP protocol. This sample works on local
machine but you can use the same code on a network. All you need to do is change the IP address of the host.

Next Recommended Article


Applied C#.NET Socket Programming

This article explains the key networking concepts, for instance ISO stack, of TCP/IP under the C# framework by employing its essential socket classes and how
applications can logically and physically be distributed in a network environment.
.NET Core Sockets Socket C# Socket Programming in .NET

.NET Core 3.0 New Features You Need To Know


Dottys
https://www.c-sharpcorner.com/members/dottys Become a member
C# Corner Login

Post Ask Question

1781 648.5k

View Previous Comments


16 16

Type your comment here and press Enter Key (Minimum 10 characters)

Very nice article


Adil Abdul Nov 19, 2019
1794 87 0 0 0 Reply

Nice
Ramesh Palaniappan Aug 29, 2016
190 10.9k 1.5m 3 0 Reply

good Article
Muhammad Abdul Manan Jul 29, 2015
1866 15 658 3 0 Reply

Hi I wanted some books on socket programming This is my student project I appreciate your help
farshad beiranvand Nov 15, 2012
1880 1 0 3 0 Reply

TcpListener tcpListener = new TcpListener(10); tcpListener.Start(); Socket socketForClient = tcpListener.AcceptSocket(); you must put those lines instead of the rst 3 lines in the code
of the server > (^_^)
Mazen Ahmed Apr 23, 2012
1880 1 0 3 0 Reply

it seems di cult to me
but i will try to do my best
and of cours u will help me
abass najri Oct 11, 2010
1880 1 0 3 0 Reply
Implementing a readline() on a network stream can cause problems, because there is no knowing when to stop reading. Its best to implement this as a read bu er, and use
stingbuilder to create s string, then just split it by newlines.
asd qwe Aug 28, 2010
.NET Core 3.0 New Features You Need To Know 3 0 Reply
1880 1 0
Become a member
C# Corner Login
nice code.... clari ed everything...
thanks... Post Ask Question
raghav sharma Jul 02, 2010
1880 1 0 3 0 Reply

well, nice start but it takes ages to build your complete TCP protocol, I found recently good tool to build TCP protocols in www.protocol-builder.com it generates the protocol code for
the server connection which can accept many connections from the client, but I like to understand the generated code, thank you.
Nick Bran May 08, 2010
1879 2 0 3 0 Reply

How to make the server can serve 2 or more client simultaneously? do  I need to include array for it? which part to include an array? at server part or at client part?

Rgds,
lil iza
lil iza lila Oct 29, 2009
1877 4 0 3 0 Reply

TRENDING UP

01 Sign-In Page Customization for Speci c Branding in Azure

02 Sealed Class Explained In C#

03 Learn Angular 8 Step By Step In 10 Days - HttpClient Or Ajax Call - Day Nine

04 How To Upload A File To Amazon S3 Using AWS SDK In MVC

05 Getting Started With .NET Core 3.1 - Part One

06 C# 8.0 - Default Interface Implementation - A New Feature Which Makes The Interface More Flexible

07 How To Create SSIS Catalog

08 What Can Be Done To Make Code Quality Better

09 A File System Manager From Scratch In .NET Core And VueJS

10 Learn About Extension Methods In C#


View All
About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners
.NET Core 3.0 New Features You Need To Know
C# Tutorials Common Interview Questions Stories Consultants Ideas Certi cations
Become a member
C# Corner Login
©2020 C# Corner. All contents are copyright of their authors.
Post Ask Question

S-ar putea să vă placă și