欢迎来到代码驿站!

.NET代码

当前位置:首页 > 软件编程 > .NET代码

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

时间:2021-06-29 08:26:03|栏目:.NET代码|点击:
下面的示例显示如何使用 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; 

上一篇:ASP.NET 5升级后如何删除旧版本的DNX

栏    目:.NET代码

下一篇:C#利用iTextSharp组件给PDF文档添加图片/文字水印

本文标题:使用C#开发Socket通讯的方法

本文地址:http://www.codeinn.net/misctech/149602.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有