简体   繁体   English

如何在C#中从客户端的主机名和端口号在Web服务器上创建套接字?

[英]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. 我想创建一个知道服务器的主机名和端口的Web服务器的客户端套接字。 I am asking this question from java background where you can simply write something like this 我是从Java背景中提出这个问题的,您可以在其中简单地编写如下内容

       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# ? 有没有类似的方式在C#中编写代码?

No need to reinvent the wheel if you plan to use the socket for HTTP communication. 如果您打算使用套接字进行HTTP通信,则无需重新设计轮子。 You can use the WebClient class to do the dirty work for you. 您可以使用WebClient类为您完成肮脏的工作。

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM