[C#] 간편한 Socket TCP 클라이언트 - PLC와 통신

1763 단어 C#
public class SocketClient
    {
        //  IP,  ,        Socket
        private string _ip;
        private int _port;
        private System.Net.Sockets.TcpClient _tcpClient;
        
        //      ,         
        public delegate void DelegateMessage(byte[] bytes) ;
        public event DelegateMessage OnmessageEvent;

        /// 
        ///     
        /// 
        /// IP  
        ///    
        public SocketClient(string remoteIp,int remotePort)
        {
            this._ip = remoteIp;
            this._port = remotePort;
        }

        //TCP  
        public bool Connect()
        {
            _tcpClient = new TcpClient();
            try
            {
                _tcpClient.Connect(IPAddress.Parse(_ip), _port);
                Task.Run(new Action(ReceiveMessage));//    ,      
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return true;//      
        }

        /// 
        ///     
        /// 
        ///        
        public void SendMessage(byte[] bytes)
        {
            NetworkStream networkStream = _tcpClient.GetStream();
            networkStream.Write(bytes, 0, bytes.Length);
        }


        //    
        public void ReceiveMessage()
        {
            NetworkStream networkStream = _tcpClient.GetStream();
            while (true)
            {
                byte[] buffer = new byte[8];
                int size = networkStream.Read(buffer, 0, buffer.Length);
                OnmessageEvent?.Invoke(buffer);
            }            
        }

    }

좋은 웹페이지 즐겨찾기