日期:2014-05-17 浏览次数:20799 次
//试图连接Socket.
static Socket ConnectSocket(string strHostName, int port) {
Socket socketResult = null; //返回Socket连接的对象.
IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);
foreach(IPAddress ipAddress in ipHostEntry.AddressList) { //遍历主机下的所有IP地址.
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);
Socket socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipEndPoint); //连接.
if(socket.Connected) { //判断是否连接到远程.
socketResult = socket;
break;
}
}
return socketResult;
}
//Socket发送连接,返回收到的信息.
static string SocketSendReceive(string strHostName, int port) {
string strRequest = "GET/HTTP/1.1\n主机:" + strHostName + "\n连接:关闭\n"; //将发送的字符串.
byte[] bSend = Encoding.Default.GetBytes(strRequest); //将发送解析的字节数组.
Socket socket = ConnectSocket(strHostName, port);
if(socket == null) return "连接失败";
byte[] bReceive = new byte[1024]; //存储返回的字符数组.