zoukankan      html  css  js  c++  java
  • c# 创建socket连接辅助类

    using AD.SocketForm.Model;
    using NLog;
    using System;
    using System.Net;
    using System.Net.Sockets;
    
    namespace AD.SocketForm.Service
    {
        public class SocketService
        {
            private Logger _logger = LogManager.GetCurrentClassLogger();
    
            /// <summary>
            /// 创建socket
            /// </summary>
            /// <param name="model"></param>
            /// <returns></returns>
            public Socket Create(HubModel model)
            {
                try
                {
                    // 将IP地址字符串转换为IPAddress对象
                    IPAddress ip = IPAddress.Parse(model.IP);
                    // 创建终结点EndPoint
                    IPEndPoint endPoint = new IPEndPoint(ip, model.Port);
                    // 创建Socket并连接到服务器
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    // 连接到服务器
                    socket.Connect(endPoint);
    
                    return socket;
                }
                catch (System.Exception ex)
                {
                    _logger.Error(string.Format("获取socket异常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
                }
                return null;
            }
    
            /// <summary>
            /// 关闭socket
            /// </summary>
            /// <param name="socket"></param>
            public void Close(Socket socket)
            {
                if (socket != null)
                {
                    socket.Close();
                    socket = null;
                }
            }
    
            /// <summary>
            /// 判断Socket是否已连接
            /// </summary>
            /// <param name="socket"></param>
            /// <returns></returns>
            public bool IsConnected(Socket socket)
            {
                if (socket == null || socket.Connected == false)
                {
                    return false;
                }
    
                bool blockingState = socket.Blocking;
                try
                {
                    byte[] tmp = new byte[1];
                    socket.Blocking = false;
                    socket.Send(tmp, 0, 0);
                    return true;
                }
                catch (SocketException e)
                {
                    // 产生 10035 == WSAEWOULDBLOCK 错误,说明被阻止了,但是还是连接的
                    if (e.NativeErrorCode.Equals(10035))
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("检查Socket是否可连接时异常,message:{0},stacktrace:{1}", ex.Message, ex.StackTrace));
                    return false;
                }
                finally
                {
                    socket.Blocking = blockingState;    // 恢复状态
                }
            }
        }
    }
  • 相关阅读:
    U盘PE系统下安装WIN2003和WINXP的方法(非GHOST版)
    自己做U盘急救杀毒
    Windows Server 2003 SP2 企业版 ISO 下载 629M
    解决开机关机慢问题
    一般处理程序
    [转]iframe自适应高度详解(希望对大家有用)非常经典,非同凡响
    ie6下position fixed的失效bug
    php文件上传MAX_FILE_SIZE不起作用的问题
    IE6测试网页显示空白页面
    自己写的面向过程php验证码
  • 原文地址:https://www.cnblogs.com/subendong/p/11822923.html
Copyright © 2011-2022 走看看