Socket处理发送和接收数据包,一个小实例:
using System.Net.Sockets;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ipUrl, port); //参数是接收的服务器ip地址和端口
string strReq = "UserName=admin&PassWord=123456";
byte[] cbReq = System.Text.Encoding.ASCII.GetBytes(strReq);
socket.Send(cbReq);
UInt16 sRecvBytes = 0;
byte[] cbRecvBytes = new byte[2];
socket.Receive(cbRecvBytes); //先接收2个字节(因为内容太长)
sRecvBytes = System.BitConverter.ToUInt16(cbRecvBytes, 0);
byte[] cbRecvContent = new byte[sRecvBytes];
int nDataLen = 0;
while (nDataLen < sRecvBytes) //判断包是否接收完
{
int nRet = socket.Receive(cbRecvContent, nDataLen, sRecvBytes-nDataLen, SocketFlags.None);
if (nRet <= 0)
{
break;
}
else
{
nDataLen += nRet;
}
}
socket.Close();
string strText = System.Text.Encoding.GetEncoding("gb2312").GetString(cbRecvContent); //此例子中返回的是个string字符串。