程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> 關於C# >> 使用C#開發Socket通訊代碼及教程

使用C#開發Socket通訊代碼及教程

編輯:關於C#
 

下面的示例顯示如何使用 Socket 類向 HTTP 服務器發送數據和接收響應。

[C#]
public string DoSocketGet(string server)
{
//Sets up variables and a string to write to the server
Encoding ASCII = Encoding.ASCII;
string Get = "GET / HTTP/1.1/r/nHost: " + server +
"/r/nConnection: Close/r/n/r/n";
Byte[] ByteGet = ASCII.GetBytes(Get);
Byte[] RecvBytes = new Byte[256];
String strRetPage = null;

// IPAddress and IPEndPoint represent the endpoint that will
// receive the request.
// Get the first IPAddress in the list using DNS.
IPAddress hostadd = Dns.Resolve(server).AddressList[0];
IPEndPoint EPhost = new IPEndPoint(hostadd, 80);

//Creates the Socket for sending data over TCP.
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp );

// Connects to the host using IPEndPoint.
s.Connect(EPhost);
if (!s.Connected)
{
strRetPage = "Unable to connect to host";
return strRetPage;
}

// Sends the GET text to the host.
s.Send(ByteGet, ByteGet.Length, SocketFlags.None);

// Receives the page, looping until all bytes are received
Int32 bytes = s.Receive(RecvBytes, RecvBytes.Length, 0);
strRetPage = "Default HTML page on " + server + ":/r/n";
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);

while (bytes > 0)
{
bytes = s.Receive(RecvBytes, RecvBytes.Length, SocketFlags.None);
strRetPage = strRetPage + ASCII.GetString(RecvBytes, 0, bytes);
}
//如果想立即關閉連接則調用 s.Close();
return strRetPage;
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved