【轉】http://blog.csdn.net/dingxiaowei2013/article/details/8113454
1 using System; 2 using System.Text; 3 using System.NET.Sockets; 4 using System.Net.Mail; 5 using System.Net; 6 namespace DotNet.Utilities 7 { 8 /// <summary> 9 /// 網絡操作相關的類 10 /// </summary> 11 public class NetHelper 12 { 13 #region 檢查設置的IP地址是否正確,返回正確的IP地址 14 /// <summary> 15 /// 檢查設置的IP地址是否正確,並返回正確的IP地址,無效IP地址返回"-1"。 16 /// </summary> 17 /// <param name="ip">設置的IP地址</param> 18 //public static string GetValidIP(string ip) 19 //{ 20 // if (PageValidate.IsIP(ip)) 21 // { 22 // return ip; 23 // } 24 // else 25 // { 26 // return "-1"; 27 // } 28 //} 29 #endregion 30 #region 檢查設置的端口號是否正確,返回正確的端口號 31 /// <summary> 32 /// 檢查設置的端口號是否正確,並返回正確的端口號,無效端口號返回-1。 33 /// </summary> 34 /// <param name="port">設置的端口號</param> 35 public static int GetValidPort(string port) 36 { 37 //聲明返回的正確端口號 38 int validPort = -1; 39 //最小有效端口號 40 const int MINPORT = 0; 41 //最大有效端口號 42 const int MAXPORT = 65535; 43 //檢測端口號 44 try 45 { 46 //傳入的端口號為空則拋出異常 47 if (port == "") 48 { 49 throw new Exception("端口號不能為空!"); 50 } 51 //檢測端口范圍 52 if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT)) 53 { 54 throw new Exception("端口號范圍無效!"); 55 } 56 //為端口號賦值 57 validPort = Convert.ToInt32(port); 58 } 59 catch (Exception ex) 60 { 61 string errMessage = ex.Message; 62 } 63 return validPort; 64 } 65 #endregion 66 #region 將字符串形式的IP地址轉換成IPAddress對象 67 /// <summary> 68 /// 將字符串形式的IP地址轉換成IPAddress對象 69 /// </summary> 70 /// <param name="ip">字符串形式的IP地址</param> 71 public static IPAddress StringToIPAddress(string ip) 72 { 73 return IPAddress.Parse(ip); 74 } 75 #endregion 76 #region 獲取本機的計算機名 77 /// <summary> 78 /// 獲取本機的計算機名 79 /// </summary> 80 public static string LocalHostName 81 { 82 get 83 { 84 return Dns.GetHostName(); 85 } 86 } 87 #endregion 88 #region 獲取本機的局域網IP 89 /// <summary> 90 /// 獲取本機的局域網IP 91 /// </summary> 92 public static string LANIP 93 { 94 get 95 { 96 //獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP 97 IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; 98 //如果本機IP列表為空,則返回空字符串 99 if (addressList.Length < 1) 100 { 101 return ""; 102 } 103 //返回本機的局域網IP 104 return addressList[0].ToString(); 105 } 106 } 107 #endregion 108 #region 獲取本機在Internet網絡的廣域網IP 109 /// <summary> 110 /// 獲取本機在Internet網絡的廣域網IP 111 /// </summary> 112 public static string WANIP 113 { 114 get 115 { 116 //獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP 117 IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; 118 //如果本機IP列表小於2,則返回空字符串 119 if (addressList.Length < 2) 120 { 121 return ""; 122 } 123 //返回本機的廣域網IP 124 return addressList[1].ToString(); 125 } 126 } 127 #endregion 128 #region 獲取遠程客戶機的IP地址 129 /// <summary> 130 /// 獲取遠程客戶機的IP地址 131 /// </summary> 132 /// <param name="clientSocket">客戶端的socket對象</param> 133 public static string GetClientIP(Socket clientSocket) 134 { 135 IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint; 136 return client.Address.ToString(); 137 } 138 #endregion 139 #region 創建一個IPEndPoint對象 140 /// <summary> 141 /// 創建一個IPEndPoint對象 142 /// </summary> 143 /// <param name="ip">IP地址</param> 144 /// <param name="port">端口號</param> 145 public static IPEndPoint CreateIPEndPoint(string ip, int port) 146 { 147 IPAddress ipAddress = StringToIPAddress(ip); 148 return new IPEndPoint(ipAddress, port); 149 } 150 #endregion 151 #region 創建一個TcpListener對象 152 /// <summary> 153 /// 創建一個自動分配IP和端口的TcpListener對象 154 /// </summary> 155 public static TcpListener CreateTcpListener() 156 { 157 //創建一個自動分配的網絡節點 158 IPAddress ipAddress = IPAddress.Any; 159 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0); 160 return new TcpListener(localEndPoint); 161 } 162 /// <summary> 163 /// 創建一個TcpListener對象 164 /// </summary> 165 /// <param name="ip">IP地址</param> 166 /// <param name="port">端口</param> 167 public static TcpListener CreateTcpListener(string ip, int port) 168 { 169 //創建一個網絡節點 170 IPAddress ipAddress = StringToIPAddress(ip); 171 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); 172 return new TcpListener(localEndPoint); 173 } 174 #endregion 175 #region 創建一個基於TCP協議的Socket對象 176 /// <summary> 177 /// 創建一個基於TCP協議的Socket對象 178 /// </summary> 179 public static Socket CreateTcpSocket() 180 { 181 return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 182 } 183 #endregion 184 #region 創建一個基於UDP協議的Socket對象 185 /// <summary> 186 /// 創建一個基於UDP協議的Socket對象 187 /// </summary> 188 public static Socket CreateUdpSocket() 189 { 190 return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 191 } 192 #endregion 193 #region 獲取本地終結點 194 #region 獲取TcpListener對象的本地終結點 195 /// <summary> 196 /// 獲取TcpListener對象的本地終結點 197 /// </summary> 198 /// <param name="tcpListener">TcpListener對象</param> 199 public static IPEndPoint GetLocalPoint(TcpListener tcpListener) 200 { 201 return (IPEndPoint)tcpListener.LocalEndpoint; 202 } 203 /// <summary> 204 /// 獲取TcpListener對象的本地終結點的IP地址 205 /// </summary> 206 /// <param name="tcpListener">TcpListener對象</param> 207 public static string GetLocalPoint_IP(TcpListener tcpListener) 208 { 209 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; 210 return localEndPoint.Address.ToString(); 211 } 212 /// <summary> 213 /// 獲取TcpListener對象的本地終結點的端口號 214 /// </summary> 215 /// <param name="tcpListener">TcpListener對象</param> 216 public static int GetLocalPoint_Port(TcpListener tcpListener) 217 { 218 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; 219 return localEndPoint.Port; 220 } 221 #endregion 222 #region 獲取Socket對象的本地終結點 223 /// <summary> 224 /// 獲取Socket對象的本地終結點 225 /// </summary> 226 /// <param name="socket">Socket對象</param> 227 public static IPEndPoint GetLocalPoint(Socket socket) 228 { 229 return (IPEndPoint)socket.LocalEndPoint; 230 } 231 /// <summary> 232 /// 獲取Socket對象的本地終結點的IP地址 233 /// </summary> 234 /// <param name="socket">Socket對象</param> 235 public static string GetLocalPoint_IP(Socket socket) 236 { 237 IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; 238 return localEndPoint.Address.ToString(); 239 } 240 /// <summary> 241 /// 獲取Socket對象的本地終結點的端口號 242 /// </summary> 243 /// <param name="socket">Socket對象</param> 244 public static int GetLocalPoint_Port(Socket socket) 245 { 246 IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; 247 return localEndPoint.Port; 248 } 249 #endregion 250 #endregion 251 #region 綁定終結點 252 /// <summary> 253 /// 綁定終結點 254 /// </summary> 255 /// <param name="socket">Socket對象</param> 256 /// <param name="endPoint">要綁定的終結點</param> 257 public static void BindEndPoint(Socket socket, IPEndPoint endPoint) 258 { 259 if (!socket.IsBound) 260 { 261 socket.Bind(endPoint); 262 } 263 } 264 /// <summary> 265 /// 綁定終結點 266 /// </summary> 267 /// <param name="socket">Socket對象</param> 268 /// <param name="ip">服務器IP地址</param> 269 /// <param name="port">服務器端口</param> 270 public static void BindEndPoint(Socket socket, string ip, int port) 271 { 272 //創建終結點 273 IPEndPoint endPoint = CreateIPEndPoint(ip, port); 274 //綁定終結點 275 if (!socket.IsBound) 276 { 277 socket.Bind(endPoint); 278 } 279 } 280 #endregion 281 #region 指定Socket對象執行監聽 282 /// <summary> 283 /// 指定Socket對象執行監聽,默認允許的最大掛起連接數為100 284 /// </summary> 285 /// <param name="socket">執行監聽的Socket對象</param> 286 /// <param name="port">監聽的端口號</param> 287 public static void StartListen(Socket socket, int port) 288 { 289 //創建本地終結點 290 IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port); 291 //綁定到本地終結點 292 BindEndPoint(socket, localPoint); 293 //開始監聽 294 socket.Listen(100); 295 } 296 /// <summary> 297 /// 指定Socket對象執行監聽 298 /// </summary> 299 /// <param name="socket">執行監聽的Socket對象</param> 300 /// <param name="port">監聽的端口號</param> 301 /// <param name="maxConnection">允許的最大掛起連接數</param> 302 public static void StartListen(Socket socket, int port, int maxConnection) 303 { 304 //創建本地終結點 305 IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port); 306 //綁定到本地終結點 307 BindEndPoint(socket, localPoint); 308 //開始監聽 309 socket.Listen(maxConnection); 310 } 311 /// <summary> 312 /// 指定Socket對象執行監聽 313 /// </summary> 314 /// <param name="socket">執行監聽的Socket對象</param> 315 /// <param name="ip">監聽的IP地址</param> 316 /// <param name="port">監聽的端口號</param> 317 /// <param name="maxConnection">允許的最大掛起連接數</param> 318 public static void StartListen(Socket socket, string ip, int port, int maxConnection) 319 { 320 //綁定到本地終結點 321 BindEndPoint(socket, ip, port); 322 //開始監聽 323 socket.Listen(maxConnection); 324 } 325 #endregion 326 #region 連接到基於TCP協議的服務器 327 /// <summary> 328 /// 連接到基於TCP協議的服務器,連接成功返回true,否則返回false 329 /// </summary> 330 /// <param name="socket">Socket對象</param> 331 /// <param name="ip">服務器IP地址</param> 332 /// <param name="port">服務器端口號</param> 333 public static bool Connect(Socket socket, string ip, int port) 334 { 335 try 336 { 337 //連接服務器 338 socket.Connect(ip, port); 339 //檢測連接狀態 340 return socket.Poll(-1, SelectMode.SelectWrite); 341 } 342 catch (SocketException ex) 343 { 344 throw new Exception(ex.Message); 345 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 346 } 347 } 348 #endregion 349 #region 以同步方式發送消息 350 /// <summary> 351 /// 以同步方式向指定的Socket對象發送消息 352 /// </summary> 353 /// <param name="socket">socket對象</param> 354 /// <param name="msg">發送的消息</param> 355 public static void SendMsg(Socket socket, byte[] msg) 356 { 357 //發送消息 358 socket.Send(msg, msg.Length, SocketFlags.None); 359 } 360 /// <summary> 361 /// 使用UTF8編碼格式以同步方式向指定的Socket對象發送消息 362 /// </summary> 363 /// <param name="socket">socket對象</param> 364 /// <param name="msg">發送的消息</param> 365 public static void SendMsg(Socket socket, string msg) 366 { 367 //將字符串消息轉換成字符數組 368 byte[] buffer = ConvertHelper.StringToBytes(msg, Encoding.Default); 369 //發送消息 370 socket.Send(buffer, buffer.Length, SocketFlags.None); 371 } 372 #endregion 373 #region 以同步方式接收消息 374 /// <summary> 375 /// 以同步方式接收消息 376 /// </summary> 377 /// <param name="socket">socket對象</param> 378 /// <param name="buffer">接收消息的緩沖區</param> 379 public static void ReceiveMsg(Socket socket, byte[] buffer) 380 { 381 socket.Receive(buffer); 382 } 383 /// <summary> 384 /// 以同步方式接收消息,並轉換為UTF8編碼格式的字符串,使用5000字節的默認緩沖區接收。 385 /// </summary> 386 /// <param name="socket">socket對象</param> 387 public static string ReceiveMsg(Socket socket) 388 { 389 //定義接收緩沖區 390 byte[] buffer = new byte[5000]; 391 //接收數據,獲取接收到的字節數 392 int receiveCount = socket.Receive(buffer); 393 //定義臨時緩沖區 394 byte[] tempBuffer = new byte[receiveCount]; 395 //將接收到的數據寫入臨時緩沖區 396 Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount); 397 //轉換成字符串,並將其返回 398 return ConvertHelper.BytesToString(tempBuffer, Encoding.Default); 399 } 400 #endregion 401 #region 關閉基於Tcp協議的Socket對象 402 /// <summary> 403 /// 關閉基於Tcp協議的Socket對象 404 /// </summary> 405 /// <param name="socket">要關閉的Socket對象</param> 406 public static void Close(Socket socket) 407 { 408 try 409 { 410 //禁止Socket對象接收和發送數據 411 socket.Shutdown(SocketShutdown.Both); 412 } 413 catch (SocketException ex) 414 { 415 throw ex; 416 } 417 finally 418 { 419 //關閉Socket對象 420 socket.Close(); 421 } 422 } 423 #endregion 424 #region 發送電子郵件 425 /// <summary> 426 /// 發送電子郵件,所有SMTP配置信息均在config配置文件中system.net節設置. 427 /// </summary> 428 /// <param name="receiveEmail">接收電子郵件的地址</param> 429 /// <param name="msgSubject">電子郵件的標題</param> 430 /// <param name="msgBody">電子郵件的正文</param> 431 /// <param name="IsEnableSSL">是否開啟SSL</param> 432 public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL) 433 { 434 //創建電子郵件對象 435 MailMessage email = new MailMessage(); 436 //設置接收人的電子郵件地址 437 email.To.Add(receiveEmail); 438 //設置郵件的標題 439 email.Subject = msgSubject; 440 //設置郵件的正文 441 email.Body = msgBody; 442 //設置郵件為HTML格式 443 email.IsBodyHtml = true; 444 //創建SMTP客戶端,將自動從配置文件中獲取SMTP服務器信息 445 SmtpClient smtp = new SmtpClient(); 446 //開啟SSL 447 smtp.EnableSsl = IsEnableSSL; 448 try 449 { 450 //發送電子郵件 451 smtp.Send(email); 452 return true; 453 } 454 catch (Exception ex) 455 { 456 throw ex; 457 } 458 } 459 #endregion 460 } 461 }
using System;
using System.Text;
using System.NET.Sockets;
using System.Net.Mail;
using System.Net;
namespace DotNet.Utilities
{
/// <summary>
/// 網絡操作相關的類
/// </summary>
public class NetHelper
{
#region 檢查設置的IP地址是否正確,返回正確的IP地址
/// <summary>
/// 檢查設置的IP地址是否正確,並返回正確的IP地址,無效IP地址返回"-1"。
/// </summary>
/// <param name="ip">設置的IP地址</param>
//public static string GetValidIP(string ip)
//{
// if (PageValidate.IsIP(ip))
// {
// return ip;
// }
// else
// {
// return "-1";
// }
//}
#endregion
#region 檢查設置的端口號是否正確,返回正確的端口號
/// <summary>
/// 檢查設置的端口號是否正確,並返回正確的端口號,無效端口號返回-1。
/// </summary>
/// <param name="port">設置的端口號</param>
public static int GetValidPort(string port)
{
//聲明返回的正確端口號
int validPort = -1;
//最小有效端口號
const int MINPORT = 0;
//最大有效端口號
const int MAXPORT = 65535;
//檢測端口號
try
{
//傳入的端口號為空則拋出異常
if (port == "")
{
throw new Exception("端口號不能為空!");
}
//檢測端口范圍
if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT))
{
throw new Exception("端口號范圍無效!");
}
//為端口號賦值
validPort = Convert.ToInt32(port);
}
catch (Exception ex)
{
string errMessage = ex.Message;
}
return validPort;
}
#endregion
#region 將字符串形式的IP地址轉換成IPAddress對象
/// <summary>
/// 將字符串形式的IP地址轉換成IPAddress對象
/// </summary>
/// <param name="ip">字符串形式的IP地址</param>
public static IPAddress StringToIPAddress(string ip)
{
return IPAddress.Parse(ip);
}
#endregion
#region 獲取本機的計算機名
/// <summary>
/// 獲取本機的計算機名
/// </summary>
public static string LocalHostName
{
get
{
return Dns.GetHostName();
}
}
#endregion
#region 獲取本機的局域網IP
/// <summary>
/// 獲取本機的局域網IP
/// </summary>
public static string LANIP
{
get
{
//獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
//如果本機IP列表為空,則返回空字符串
if (addressList.Length < 1)
{
return "";
}
//返回本機的局域網IP
return addressList[0].ToString();
}
}
#endregion
#region 獲取本機在Internet網絡的廣域網IP
/// <summary>
/// 獲取本機在Internet網絡的廣域網IP
/// </summary>
public static string WANIP
{
get
{
//獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
//如果本機IP列表小於2,則返回空字符串
if (addressList.Length < 2)
{
return "";
}
//返回本機的廣域網IP
return addressList[1].ToString();
}
}
#endregion
#region 獲取遠程客戶機的IP地址
/// <summary>
/// 獲取遠程客戶機的IP地址
/// </summary>
/// <param name="clientSocket">客戶端的socket對象</param>
public static string GetClientIP(Socket clientSocket)
{
IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;
return client.Address.ToString();
}
#endregion
#region 創建一個IPEndPoint對象
/// <summary>
/// 創建一個IPEndPoint對象
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="port">端口號</param>
public static IPEndPoint CreateIPEndPoint(string ip, int port)
{
IPAddress ipAddress = StringToIPAddress(ip);
return new IPEndPoint(ipAddress, port);
}
#endregion
#region 創建一個TcpListener對象
/// <summary>
/// 創建一個自動分配IP和端口的TcpListener對象
/// </summary>
public static TcpListener CreateTcpListener()
{
//創建一個自動分配的網絡節點
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0);
return new TcpListener(localEndPoint);
}
/// <summary>
/// 創建一個TcpListener對象
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="port">端口</param>
public static TcpListener CreateTcpListener(string ip, int port)
{
//創建一個網絡節點
IPAddress ipAddress = StringToIPAddress(ip);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
return new TcpListener(localEndPoint);
}
#endregion
#region 創建一個基於TCP協議的Socket對象
/// <summary>
/// 創建一個基於TCP協議的Socket對象
/// </summary>
public static Socket CreateTcpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
#endregion
#region 創建一個基於UDP協議的Socket對象
/// <summary>
/// 創建一個基於UDP協議的Socket對象
/// </summary>
public static Socket CreateUdpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
#endregion
#region 獲取本地終結點
#region 獲取TcpListener對象的本地終結點
/// <summary>
/// 獲取TcpListener對象的本地終結點
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static IPEndPoint GetLocalPoint(TcpListener tcpListener)
{
return (IPEndPoint)tcpListener.LocalEndpoint;
}
/// <summary>
/// 獲取TcpListener對象的本地終結點的IP地址
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static string GetLocalPoint_IP(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// 獲取TcpListener對象的本地終結點的端口號
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static int GetLocalPoint_Port(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Port;
}
#endregion
#region 獲取Socket對象的本地終結點
/// <summary>
/// 獲取Socket對象的本地終結點
/// </summary>
/// <param name="socket">Socket對象</param>
public static IPEndPoint GetLocalPoint(Socket socket)
{
return (IPEndPoint)socket.LocalEndPoint;
}
/// <summary>
/// 獲取Socket對象的本地終結點的IP地址
/// </summary>
/// <param name="socket">Socket對象</param>
public static string GetLocalPoint_IP(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// 獲取Socket對象的本地終結點的端口號
/// </summary>
/// <param name="socket">Socket對象</param>
public static int GetLocalPoint_Port(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Port;
}
#endregion
#endregion
#region 綁定終結點
/// <summary>
/// 綁定終結點
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="endPoint">要綁定的終結點</param>
public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
{
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
/// <summary>
/// 綁定終結點
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="ip">服務器IP地址</param>
/// <param name="port">服務器端口</param>
public static void BindEndPoint(Socket socket, string ip, int port)
{
//創建終結點
IPEndPoint endPoint = CreateIPEndPoint(ip, port);
//綁定終結點
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
#endregion
#region 指定Socket對象執行監聽
/// <summary>
/// 指定Socket對象執行監聽,默認允許的最大掛起連接數為100
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="port">監聽的端口號</param>
public static void StartListen(Socket socket, int port)
{
//創建本地終結點
IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);
//綁定到本地終結點
BindEndPoint(socket, localPoint);
//開始監聽
socket.Listen(100);
}
/// <summary>
/// 指定Socket對象執行監聽
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="port">監聽的端口號</param>
/// <param name="maxConnection">允許的最大掛起連接數</param>
public static void StartListen(Socket socket, int port, int maxConnection)
{
//創建本地終結點
IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);
//綁定到本地終結點
BindEndPoint(socket, localPoint);
//開始監聽
socket.Listen(maxConnection);
}
/// <summary>
/// 指定Socket對象執行監聽
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="ip">監聽的IP地址</param>
/// <param name="port">監聽的端口號</param>
/// <param name="maxConnection">允許的最大掛起連接數</param>
public static void StartListen(Socket socket, string ip, int port, int maxConnection)
{
//綁定到本地終結點
BindEndPoint(socket, ip, port);
//開始監聽
socket.Listen(maxConnection);
}
#endregion
#region 連接到基於TCP協議的服務器
/// <summary>
/// 連接到基於TCP協議的服務器,連接成功返回true,否則返回false
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="ip">服務器IP地址</param>
/// <param name="port">服務器端口號</param>
public static bool Connect(Socket socket, string ip, int port)
{
try
{
//連接服務器
socket.Connect(ip, port);
//檢測連接狀態
return socket.Poll(-1, SelectMode.SelectWrite);
}
catch (SocketException ex)
{
throw new Exception(ex.Message);
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
}
}
#endregion
#region 以同步方式發送消息
/// <summary>
/// 以同步方式向指定的Socket對象發送消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="msg">發送的消息</param>
public static void SendMsg(Socket socket, byte[] msg)
{
//發送消息
socket.Send(msg, msg.Length, SocketFlags.None);
}
/// <summary>
/// 使用UTF8編碼格式以同步方式向指定的Socket對象發送消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="msg">發送的消息</param>
public static void SendMsg(Socket socket, string msg)
{
//將字符串消息轉換成字符數組
byte[] buffer = ConvertHelper.StringToBytes(msg, Encoding.Default);
//發送消息
socket.Send(buffer, buffer.Length, SocketFlags.None);
}
#endregion
#region 以同步方式接收消息
/// <summary>
/// 以同步方式接收消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="buffer">接收消息的緩沖區</param>
public static void ReceiveMsg(Socket socket, byte[] buffer)
{
socket.Receive(buffer);
}
/// <summary>
/// 以同步方式接收消息,並轉換為UTF8編碼格式的字符串,使用5000字節的默認緩沖區接收。
/// </summary>
/// <param name="socket">socket對象</param>
public static string ReceiveMsg(Socket socket)
{
//定義接收緩沖區
byte[] buffer = new byte[5000];
//接收數據,獲取接收到的字節數
int receiveCount = socket.Receive(buffer);
//定義臨時緩沖區
byte[] tempBuffer = new byte[receiveCount];
//將接收到的數據寫入臨時緩沖區
Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount);
//轉換成字符串,並將其返回
return ConvertHelper.BytesToString(tempBuffer, Encoding.Default);
}
#endregion
#region 關閉基於Tcp協議的Socket對象
/// <summary>
/// 關閉基於Tcp協議的Socket對象
/// </summary>
/// <param name="socket">要關閉的Socket對象</param>
public static void Close(Socket socket)
{
try
{
//禁止Socket對象接收和發送數據
socket.Shutdown(SocketShutdown.Both);
}
catch (SocketException ex)
{
throw ex;
}
finally
{
//關閉Socket對象
socket.Close();
}
}
#endregion
#region 發送電子郵件
/// <summary>
/// 發送電子郵件,所有SMTP配置信息均在config配置文件中system.net節設置.
/// </summary>
/// <param name="receiveEmail">接收電子郵件的地址</param>
/// <param name="msgSubject">電子郵件的標題</param>
/// <param name="msgBody">電子郵件的正文</param>
/// <param name="IsEnableSSL">是否開啟SSL</param>
public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL)
{
//創建電子郵件對象
MailMessage email = new MailMessage();
//設置接收人的電子郵件地址
email.To.Add(receiveEmail);
//設置郵件的標題
email.Subject = msgSubject;
//設置郵件的正文
email.Body = msgBody;
//設置郵件為HTML格式
email.IsBodyHtml = true;
//創建SMTP客戶端,將自動從配置文件中獲取SMTP服務器信息
SmtpClient smtp = new SmtpClient();
//開啟SSL
smtp.EnableSsl = IsEnableSSL;
try
{
//發送電子郵件
smtp.Send(email);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}