Home »
.Net »
C# Programs
Socket Client Program in C#
Learn, how to create a socket client program using C#?
By Nidhi Last updated : April 03, 2023
Creating a socket client
Here, we will create a socket client program, that connects to the socket server, and then we can send or receive data in a network.
C# program to create a socket client
The source code to create a socket client program is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
class SocketClient {
static void Main(string[] args) {
TcpClient client = new TcpClient();
ASCIIEncoding encoding = new ASCIIEncoding();
Stream stream;
string sendStr = "Hello";
int recvLen = 0;
byte[] sendByteArray;
byte[] recvByteArray = new byte[256];
Console.WriteLine("Connecting.....");
client.Connect("127.0.0.1", 15001);
Console.WriteLine("Connected to server");
stream = client.GetStream();
sendByteArray = encoding.GetBytes(sendStr);
stream.Write(sendByteArray, 0, sendByteArray.Length);
Console.WriteLine("Data send...");
recvLen = stream.Read(recvByteArray, 0, 100);
for (int i = 0; i < recvLen; i++)
Console.Write(Convert.ToChar(recvByteArray[i]));
client.Close();
Console.WriteLine();
}
}
Output
Connecting.....
Connected to server
Data send...
data received
Press any key to continue . . .
Explanation
In the above program, we created a socket client program, that will connect to the socket server using the Hercules tool on localhost with port 15001, and then we can send and receive data over the network.
Here, we can replace the localhost IP address with a specific IP address.
C# Socket Programs »