How to create a socket on client side to web server from its hostname and Port number in C#?

I want to create a client socket to a web server knowing its hostname and port. I am asking this question from java background where you can simply write something like this

       Socket MyClient;
       try 
       {
            MyClient = new Socket("Hostname", PortNumber);
       }
      catch (IOException e) 
       {
            System.out.println(e);
       }

Is there a similar way to write that in C# ?

Answers


No need to reinvent the wheel if you plan to use the socket for HTTP communication. You can use the WebClient class to do the dirty work for you.


here sample for you.

   private string getHTTP(string url)
    {
        TcpClient clientSocket = new TcpClient();
        NetworkStream networkStream = null;
        long port = 7777;
        try
        {
            try
            {

                clientSocket.Connect(url,port );
            }
            catch { MessageBox.Show("Server is not Working", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return "Server is not working"; }
            byte[] sendbyte = Encoding.ASCII.GetBytes(url);

            networkStream = clientSocket.GetStream();
            networkStream.Write(sendbyte, 0, sendbyte.Length);
            networkStream.Flush();
        }
        catch { MessageBox.Show("Streaming Error", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Warning); return "Error"; }
        // receive Message from DNS Server
        byte[] receivedata = new byte[clientSocket.ReceiveBufferSize];
        networkStream.Read(receivedata, 0, clientSocket.ReceiveBufferSize);

        string urlnew = Encoding.ASCII.GetString(receivedata);

        return urlnew;
    }

More you should reference this link


From the answers provided an idea jumped out of my mind , this is what i think could be the simple answer:

    public Socket getSocket1(string Hostname, int PortNmber)
    {
        TcpClient client = new TcpClient(Hostname, PortNumber);
        return client.Client;
    }

Need Your Help

Why am I getting undefined for my variable in the controller but it displays correctly in the HTML page with data binding

javascript angularjs

Why am I getting values with data binding from my with {{myItem}} but in my controller when I try to assign a new variable I get or output to console I get undefined.

AS3 Creating algorithm for 6 ^ 20 results

algorithm actionscript-3 data-structures tree

I have searched a lot for something to point me in the right direction,

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.