Monday, May 13, 2013

TCP Socket Reader



using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Web;

namespace Applications.Common.Utilities
{
    public class TcpUtilities : IDisposable
    {
        #region Private members

        private Socket _socket;
        private string _serverName;
        private int _portNumber;

        #endregion

        #region Constructor/Destructor
        public TcpUtilities(string serverName, int portNumber)
        {
            _portNumber = portNumber;
            _serverName = serverName;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {

            if (disposing)
                if (_socket != null)
                {
                    _socket.Dispose();
                    _socket = null;
                }
        }
        ~TcpUtilities()
        {
            Dispose(false);
        }
        #endregion

        #region General public methods

        public void OpenSocket()
        {
            IPHostEntry hostEntry = null;
            hostEntry = Dns.GetHostEntry(_serverName);
            IPEndPoint ipe = new IPEndPoint(Dns.GetHostAddresses(_serverName)[0], _portNumber);
            _socket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.Connect(ipe);
        }

        public void CloseSocket()
        {
            if (_socket.Connected == true)
                _socket.Close();
        }

        public string SendReceive(string request)
        {

            OpenSocket();

            Byte[] bytesSent = Encoding.UTF8.GetBytes(request);

            _socket.Send(bytesSent, bytesSent.Length, SocketFlags.None);

            int bytes = 0;
            string response = "";

            // The following will block until the entire string is transmitted.
            do
            {
                Byte[] bytesReceived = new Byte[1024];
                bytes = _socket.Receive(bytesReceived, bytesReceived.Length, SocketFlags.None);
                response += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
            }
            while (bytes > 0);
            //response = HttpUtility.UrlDecode( response.Substring( response.IndexOf( '0' ) + 1 ) );
            CloseSocket();
            return response;
        }

        #endregion



    }
}



Implementation

_tcpUtilities = new TcpUtilities(_serverName, _portNumber);
        public string SendInquiry( string command , bool returnRawData )
        {
           
            string formattedQuery = FormatInquiryRequest( command );
            string result = _tcpUtilities.SendReceive( formattedQuery );
            string returnValue = DeFormatInquiryResult( result , returnRawData );

            return ( returnValue );
        }




No comments:

Post a Comment