110,538
社区成员
发帖
与我相关
我的任务
分享
public string SocketSendReceive(string[] path, int port)
{
string request = string.Format("GET /{0} HTTP/1.1\r\nHost: {1}\r\nConnection: Close\r\n\r\n", path[1], path[0]);
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[8192];
//char[] s"Content-Length: "
// Create a socket connection with the specified server and port.
Socket s = GetSocket();
if (s == null)
return ("Connection failed");
// Send request to the server.
s.Send(bytesSent, bytesSent.Length, 0);
// Receive the server home page content.
int bytes = 0;
int nRevIndex = 0;
// create sPage buffer
byte[] arrbtPage = new byte[200000];
Array.Clear(arrbtPage, 0, 200000);
// The following will block until te sPage is transmitted.
long nStartRev = DateTime.Now.Ticks;
long nEndRev = DateTime.Now.Ticks;
try
{
do
{
if (s.Poll(-1, SelectMode.SelectRead))
{
bytes = s.Receive(bytesReceived, bytesReceived.Length, SocketFlags.None);
nRevIndex = nRevIndex + bytes;
//System.Diagnostics.Debug.WriteLine("::" + bytesReceived.ToString());
Array.Copy(bytesReceived, 0, arrbtPage, nRevIndex, bytes);
//bytesReceived
}
nEndRev = DateTime.Now.Ticks;
}
while (bytes > 0 && nEndRev - nStartRev < 100000000);
// 判断是否为UTF8编码,否则为GB2312
if (Encode.IsUtf8(arrbtPage, arrbtPage.Length))
{
m_sPage.Append(Encoding.UTF8.GetString(arrbtPage));
}
else
{
m_sPage.Append(Encoding.GetEncoding(936).GetString(arrbtPage));
}
}
catch
{
return string.Empty;
}
return m_sPage.ToString();
}