完整代码:
//试图连接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]; //存储返回的字符数组.
socket.Send(bSend, SocketFlags.None);
string strReceive = strHostName + "上默认的页面内容:\n"; //存储返回的内容.
int nReceiveIndex = 0; //返回的内容的当前下标.
do {
nReceiveIndex = socket.Receive(bReceive, SocketFlags.None);
strReceive += Encoding.Default.GetString(bReceive, 0, nReceiveIndex);
} while(nReceiveIndex > 0);
return strReceive;
}
//传入远程计算机主机名和端口号.
private void btnConfirm_Click(object sender, EventArgs e) {
richTxt.Text = SocketSendReceive(txtHostName.Text.Trim(), int.Parse(txtPort.Text.Trim()));
}
运行界面图:
//试图连接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]; //存储返回的字符数组.
socket.Send(bSend, SocketFlags.None);
string strReceive = strHostName + "上默认的页面内容:\n"; //存储返回的内容.
int nReceiveIndex = 0; //返回的内容的当前下标.
do {
nReceiveIndex = socket.Receive(bReceive, SocketFlags.None);
strReceive += Encoding.Default.GetString(bReceive, 0, nReceiveIndex);
} while(nReceiveIndex > 0);
return strReceive;
}
//传入远程计算机主机名和端口号.
private void btnConfirm_Click(object sender, EventArgs e) {
richTxt.Text = SocketSendReceive(txtHostName.Text.Trim(), int.Parse(txtPort.Text.Trim()));
}
运行界面图:
Socket socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
指定的是通过流传递,但是这里又没有写对应的流出来?是Socket内部加的?
我在反编译代码中都没有找到?
因为我在 TcpClient类中有 Stream对应的方法,但是Socket没有...开始碰...有点钻牛角尖...
不能望文生义。查MSDN吧。