This tutorial will explain how to connect to a host machine, and then send data via TCP Socket.

First, we need to add the namespaces:

using System.Net;
using System.Net.Sockets;

And the function:

public static void SendData(string data, Int32 port, string ips)
{
    IPAddress host = IPAddress.Parse(ips);//  
    IPEndPoint ipendpoint = new IPEndPoint(host, port); // assign host and port                                                               
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        socket.Connect(ipendpoint);
    }
    catch (SocketException e)
    {
        MessageBox.Show(e.Message);

        socket.Close();
        return;
    }
    try
    {
        socket.Send(Encoding.ASCII.GetBytes(data));
    }
    catch (SocketException e)
    {
        MessageBox.Show(e.Message);
        socket.Close();
        return;
    }
    socket.Close();
}

Then call the function:

SendData("Hello World!", 1212,"127.0.0.1");

Note: The port should be listening. To check that, open the Command Prompt, then type netstat –an and hit enter.

Possible Errors:

Error 1:
No connection could be made because the target machine actively refused it 127.0.0.1:1212.

Cause: A nonexisting port or the part is not listening.

Error 2:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 122.4.0.3:1212

Cause: Host name doesn’t exist.

 

Last modified: March 8, 2019

Comments

Write a Reply or Comment

Your email address will not be published.