下面的示例显示如何使用 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;
}
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
C#实现猜数字游戏
本文实例为大家分享了c#实现猜数字游戏具体代码,供大家参考,具体内容如下给定一个0-100的随机数字猜其大小题目样式:电脑产生一个0到100之间的随机数字,并且...
[阅读全文]
-
-
C# 可空类型的具体使用
在项目中我们经常会遇到可为空类型,那么到底什么是可为空类型呢?下面我们将从4个方面为大家剖析。1、可空类型基础知识顾名思义,可空类型指的就是某个对象类型可以为空...
[阅读全文]
-
-
-
C#实现猜数字小游戏
本文实例为大家分享了c#实现猜数字小游戏的具体代码,供大家参考,具体内容如下效果如图:代码:using system;using system.collecti...
[阅读全文]
-
-
C#实现简单俄罗斯方块
最近在看《.net游戏编程入门经典 c#篇》 第一章介绍了如何制作俄罗斯方块,自己试了试按照书上的步骤,可算是完成了。于是写下这篇文章留作纪念。1.类的设计在充...
[阅读全文]
-
-
网友评论