欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用C#开发Socket通讯的方法

程序员文章站 2023-11-09 14:01:10
下面的示例显示如何使用 socket 类向 http 服务器发送数据和接收响应。  [c#]  public&n...
下面的示例显示如何使用 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;