2011-12-17 64 views
0

我想創建一個知道其主機名和端口的Web服務器的客戶端套接字。我問從Java背景這個問題,在這裏你可以簡單地寫這樣的事情如何從客戶端的主機名和C#端口號在Web服務器上創建一個套接字?

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

有沒有寫在C#中的類似的方式?

+0

將插座打開使用HTTP進行通信?你看過HttpWebClient類嗎? http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx – 2011-12-17 03:38:19

+0

是的套​​接字將使用HTTP通信! – Xris 2011-12-17 04:01:56

回答

0

如果您計劃使用套接字進行HTTP通信,則無需重新發明輪子。您可以使用WebClient課爲您做髒活。

0

這裏是你的樣品。

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

更應該參考this link

0

從提供的答案的想法跳出我的腦海,這就是我想可能是簡單的答案:

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