Common.TcpLibTcpClientS

using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.InteropServices;
using System.IO;

namespace Common.TcpLib
{
    /// <summary>
    /// 同步Socket处理客户端 专用于短连接处理
    /// </summary>
    public class TcpClientS
    {
        public Socket _clientSocket;
        private string _serverIp;
        private int _port;
        private int _bufferSize = 1024;

        private bool _disposed = false;
        private bool _debug = false;

        #region define delegates
        /// <summary>
        /// 连接上服务器后的事件处理
        /// </summary>
        public _Bgz_OnConnectEventDelegate FOnConnectEventDelegate;

        /// <summary>
        /// 接收服务端发来的数据事件处理
        /// </summary>
        public _Bgz_OnReceiveBeginEventDelegate FOnReceiveBeginEventDelegate;

        /// <summary>
        /// 接收服务端发来的数据事件处理
        /// </summary>
        public _Bgz_OnReceiveingEventDelegate FOnReceiveingEventDelegate;

        /// <summary>
        /// 接收服务端发来的数据事件处理
        /// </summary>
        public _Bgz_OnReceiveEndEventDelegate FOnReceiveEndEventDelegate;

        /// <summary>
        /// 报错信息处理
        /// </summary>
        public _Bgz_OnErrorEventDelegate FOnErrorEventDelegate;
        #endregion

        #region Event
        private void OnConnectEvent(_Bgz_ConnectionState state)
        {
            if (FOnConnectEventDelegate != null) FOnConnectEventDelegate(state);
        }
        private void OnReceiveBeginEvent(_Bgz_ConnectionState state)
        {
            if (FOnReceiveBeginEventDelegate != null) FOnReceiveBeginEventDelegate(state);
        }
        private void OnReceiveingEvent(_Bgz_ConnectionState state)
        {
            if (FOnReceiveingEventDelegate != null) FOnReceiveingEventDelegate(state);
        }
        private void OnReceiveEndEvent(_Bgz_ConnectionState state)
        {
            if (FOnReceiveEndEventDelegate != null) FOnReceiveEndEventDelegate(state);
        }
        private void OnErrorEvent(ErrorType errortype, string msg, _Bgz_ConnectionState state)
        {
            if (FOnErrorEventDelegate != null) FOnErrorEventDelegate(errortype, msg, state);
        }
        #endregion

        #region property

        public int BufferSize
        {
            get
            {
                return _bufferSize;
            }
        }

        public bool Debug
        {
            get
            {
                return _debug;
            }
            set
            {
                _debug = value;
            }
        }
        #endregion

        #region Constructor and Destructor

        public TcpClientS(string serverIp, int port)
        {
            this._serverIp = serverIp;
            this._port = port;
        }

        public TcpClientS(string serverIp, int port, int bufferSize)
        {
            this._serverIp = serverIp;
            this._port = port;
            this._bufferSize = bufferSize;
        }

        ~TcpClientS()
        {
        }
        #endregion

        #region Private Methods
        private void Dispose()
        {
            if (!_disposed)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                this.FOnConnectEventDelegate = null;
                this.FOnErrorEventDelegate = null;
                this.FOnReceiveBeginEventDelegate = null;
                this.FOnReceiveEndEventDelegate = null;
                this.FOnReceiveingEventDelegate = null;
                _disposed = true;
            }
        }
        #endregion

        #region Public Methods

        public byte[] SendAsOdian(byte[] msg)
        {
            return SendAsOdian(msg, 60000);
        }

        public byte[] SendAsOdian(byte[] msg, int ReceiveTimeout)
        {

            #region 阻止Socket发送空字节信息
            if (msg == null || msg.Length == 0) return null;
            #endregion

            _Bgz_ConnectionState stx = new _Bgz_ConnectionState();

            #region Connect
            try
            {
                stx._conn = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                stx._conn.Connect(new IPEndPoint(IPAddress.Parse(_serverIp), _port));
                stx._conn.LingerState = new LingerOption(false, 3);

                #region 设置Socket接收延时的处理
                stx._conn.ReceiveTimeout = ReceiveTimeout;
                #endregion

                OnConnectEvent(stx);
            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "SendAsOdian.1 Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
                return null;
            }
            #endregion

            try
            {
                stx._conn.Send(msg);

                #region read to bytes

                stx._buffer = new byte[0];
                stx._count = 0;
                stx._getonceall = false;
                stx._conn.Receive(stx._buffer);

                if (stx._conn.Available == 0)
                {
                    if (Debug)
                    {
                        OnErrorEvent(ErrorType.Catch, "关闭与服务器的连接!", null);
                    }
                    stx._conn.Shutdown(SocketShutdown.Both);
                    stx._conn.Close();
                    return stx._buffer;
                }

                OnReceiveBeginEvent(stx);

                stx._count = 0;
                stx._dataStream.SetLength(0);
                stx._dataStream.Position = 0;
                if (stx._getonceall)
                {
                    stx._buffer = new byte[stx._conn.Available];
                    int ret = stx._conn.Receive(stx._buffer, 0, stx._buffer.Length, SocketFlags.None);
                    if (ret > 0)
                    {
                        stx._dataStream.Write(stx._buffer, 0, stx._buffer.Length);
                        stx._count++;
                        OnReceiveingEvent(stx);
                    }
                }
                else
                {
                    while (stx._conn.Available > 0)
                    {
                        if (stx._conn.Available > this._bufferSize)
                            stx._buffer = new byte[this._bufferSize];
                        else
                            stx._buffer = new byte[stx._conn.Available];
                        int ret = stx._conn.Receive(stx._buffer, 0, stx._buffer.Length, SocketFlags.None);
                        if (ret > 0)
                        {
                            stx._dataStream.Write(stx._buffer, 0, stx._buffer.Length);
                            stx._count++;
                            OnReceiveingEvent(stx);
                        }
                    }
                }

                OnReceiveEndEvent(stx);
                #endregion


            }
            catch (Exception ex)
            {
                if (Debug)
                {
                    OnErrorEvent(ErrorType.Catch, "SendAsOdian.2 Error![Message]:\r\n" + ex.Message + "[StackTrace]:\r\n" + ex.StackTrace + "\r\n", null);
                }
            }
            finally
            {
                if (stx._conn != null)
                    if (stx._conn.Connected)
                    {
                        stx._conn.Shutdown(SocketShutdown.Both);
                        stx._conn.Close();
                    }
                OnErrorEvent(ErrorType.DisConnect, "关闭与服务器的连接!", null);
            }

            return stx._buffer;
        }

        #endregion
    }

}

转载于:https://www.cnblogs.com/bigmouthz/archive/2007/11/01/946189.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值