首页 > 编程 > .NET > 正文

[ASP.NET]使用C#开发Socket通讯

2024-07-10 13:00:16
字体:
来源:转载
供稿:网友
下面的示例显示如何使用 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;
}

国内最大的酷站演示中心!
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表