Пример #1
0
        public static void Start()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);

            listener.Bind(new IPEndPoint(IPAddress.Any, PORT));

            Console.WriteLine("Waiting for a connection..." + GetLocalIpAddress());

            while (true) {

                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                StateObject state = new StateObject();
                state.WorkSocket = listener;
                listener.ReceiveFrom(state.Buffer, ref remoteEndPoint);
                var rawMessage = Encoding.UTF8.GetString(state.Buffer);
                var messages = rawMessage.Split(';');

                if (messages.Length > 1) {
                    var command = messages[0];
                    var deviceName = messages[1];
                    Console.WriteLine("Command is received from Device Name +"+deviceName+"+");
                    string[] portno = remoteEndPoint.ToString().Split(':');
                    Send(portno[1],remoteEndPoint);

                }
            }
        }
Пример #2
0
        public bool Start()
        {
            if (_started) return true;

            _socket = SocketUtils.OpenSocketConnection("api.triggrapp.com", 9090);

            if (_socket == null)
            {
                _started = false;
                return false;
            }

            _started = true;

            StateObject state = new StateObject();
            state.workSocket = _socket;

            _socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);

            SendHandshake();

            StartHeartbeat();

            return true;
        }
Пример #3
0
        public SyncSocClient(string _ipAddress, int port, int timeout)
        {

            try
            {
                IPAddress ipAddress = System.Net.IPAddress.Parse(_ipAddress);
                mPort = port;
                remoteEP = new IPEndPoint(ipAddress, mPort);

                mSender = new Socket(AddressFamily.InterNetwork,
                                        SocketType.Stream, ProtocolType.Tcp);

                if (timeout > 0)
                {
                    mSender.ReceiveTimeout = timeout;
                    mSender.SendTimeout = timeout;
                }
                //mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout);

                // The socket will linger for 10 seconds after Socket.Close is called.
                LingerOption lingerOption = new LingerOption(true, 10);

                mSender.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                stateObj = new StateObject(mSender);
            }
            catch (Exception e)
            {
                SetErrorMessage(e, string.Format("소켓생성Error ip[{0}]/port[{1}]/timeout[{2}]]",_ipAddress,port,timeout));
                Logger.error(e.ToString());
            }
        }
Пример #4
0
        private bool Connect(StateObject stateObject) {
            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(hostIp), hostPort);

            stateObject.workSocket = client;

            int retry = retryTime;
            while (true) {
                try {
                    // Connect to the remote endpoint.
                    client.Connect(ipEndPoint);
                    break;
                } catch (Exception be) {
                    retry--;
                    Logging.LogError(be.Message);
                    Logging.LogError("Retry time: " + retry);
                }
                if (retry <= 0) {
                    Logging.LogError("Connecntion Error.");
                    return false;
                }
            }

            client.SendTimeout = timeout;
            client.ReceiveTimeout = timeout;

            return true;
        }
Пример #5
0
        public Object start(TransferObject to) {
            Object resultObject = null;

            String calleeClass = to.getCalleeClass();
            String calleeMethod = to.getCalleeMethod();

            StateObject stateObject = new StateObject();
            stateObject.transferObject = to;

            try {
                if (Connect(stateObject)) {

                    Send(stateObject);

                    resultObject = Receive(stateObject);
                }
            } catch (Exception e) {
                Logging.LogError("Callee Class and Method: [" + calleeClass + "." + calleeMethod + "]");
                Logging.LogError(e.ToString());
            } finally {
                Close(stateObject);
            }

            return resultObject;
        }
Пример #6
0
        public Connection(Server server, Socket socket)
        {
            m_Server = server;
            m_Socket = socket;

            var state = new StateObject { Socket = m_Socket };
            m_Socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
        }
Пример #7
0
 public string ReadMessage(Socket client)
 {
     StateObject state = new StateObject();
     state.workSocket = client;
     client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
     readDone.WaitOne();
     readDone.Reset();
     return state.sb.ToString();
 }
Пример #8
0
        public void AcceptCallback(IAsyncResult ar)
        {
            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            AskForReceive(handler, state);
        }
Пример #9
0
 //get the done state of a partial docket.
 private static bool getPartialDocketState(BindingList<object> partialDocket)
 {
     bool state = true;
     for (int i = 1; i < partialDocket.Count; i++) {
         if (!((Order)partialDocket[i]).Done) {
             state = false;
             break;
         }
     }
     return state;
 }
Пример #10
0
        IAsyncResult BeginConnect(AsyncCallback requestCallback, object userToken)
        {
            var stateObject = new StateObject()
            {
                AsyncState = userToken,
                Callback = requestCallback,
                IsCompleted = false
            };

            this.ConnectAsync(stateObject);
            return stateObject;
        }
Пример #11
0
        public void StartReceiving()
        {
            if (OnNotifyMulticastSocketListener == null)
            throw new ApplicationException("No socket listener has been specified at OnNotifyMulticastSocketListener.");

              // Create the state object.
              StateObject state = new StateObject();
              state.WorkSocket = udpSocket;

              //get in waiting mode for data - always (this doesn't halt code execution)
              Recieve(state);
        }
Пример #12
0
 // Method passed to ThreadStart.
 //
 // This is the thread's starting point. It starts the process on the server machine, creates three ``state objects'', which will
 // help us handle the redirections asynchronously. We associate the BeginRead methods of the standard output and error streams
 // with our call-back (LocalReadCallback), to start processing the output of the command. We also associate the BeginRead() method
 // the socket to our socket read call-back (ReadCallback), so we can process the data received through the socket.
 public void DoWork()
 {
     Process process = Process.Start(_processStartInfo);
         LocalStateObject outputLocalStateObject = new LocalStateObject(_socket, process, process.StandardOutput.BaseStream);
         process.StandardOutput.BaseStream.BeginRead(outputLocalStateObject.Buffer, 0, LocalStateObject.BUFFER_SIZE, new AsyncCallback(LocalReadCallback), outputLocalStateObject);
         LocalStateObject errorLocalStateObject = new LocalStateObject(_socket, process, process.StandardError.BaseStream);
         process.StandardError.BaseStream.BeginRead(errorLocalStateObject.Buffer, 0, LocalStateObject.BUFFER_SIZE, new AsyncCallback(LocalReadCallback), errorLocalStateObject);
         StateObject stateObject = new StateObject(_socket, process);
         _socket.BeginReceive(stateObject.Buffer, 0, StateObject.BUFFER_SIZE, 0, new AsyncCallback(ReadCallback), stateObject);
         process.WaitForExit();
         _socket.Close();
 }
            public static void AcceptCallback(IAsyncResult ar)
            {
                allDone.Set();

                Socket listener = (Socket)ar.AsyncState;
                Socket handler = listener.EndAccept(ar);

                StateObject state = new StateObject();
                state.workSocket = handler;
                handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReadCallback), state);
            }
Пример #14
0
 void ConnectAsync(StateObject stateObject)
 {
     var e = new SocketAsyncEventArgs();
     e.UserToken = stateObject;
     e.RemoteEndPoint = _endpoint;
     e.Completed += OnConnectedAsync;
     try
     {
         this.Client.ConnectAsync(e);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + " >" + ex.StackTrace);
     }
 }
Пример #15
0
        public void AcceptCallback(IAsyncResult ar)
        {

            allDone.Set();


            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);


            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, ReadCallbackFileRecive, state);
            flag = 0;
        }
        public static void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.
            allDone.Set();

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }
        public void AcceptCallback(IAsyncResult ar)
        {
            // Signal the main thread to continue.

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            connectedClients.Add(handler);
            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
                new AsyncCallback(DealCallback), state);
            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
        }
Пример #18
0
        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());

            }
        }
Пример #19
0
        // This is the call back function, which will be invoked when a client is connected
        public void OnClientConnect(IAsyncResult asyn)
        {
            try
            {
                // Here we complete/end the BeginAccept() asynchronous call
                // by calling EndAccept() - which returns the reference to
                // a new Socket object

                Socket handler = m_mainSocket.EndAccept(asyn);
                // Let the worker Socket do the further processing for the 
                // just connected client
                StateObject state = new StateObject();
                state.socket = handler;
                state.id = m_workerSocket.Count;

                m_workerSocket.Add(state);
                try
                {
                    handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
                }
                catch (SocketException se)
                {
                    //MessageBox.Show(se.Message);
                }

                // Display this client connection as a status message on the GUI	
                String str = String.Format("Client # {0} connected", m_workerSocket.Count - 1);

                // Since the main Socket is now free, it can go back and wait for
                // other clients who are attempting to connect
                m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);

            }
            catch (ObjectDisposedException)
            {
                
            }
            catch (SocketException se)
            {
                
            }
        }
Пример #20
0
        public string Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                var wait =  client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
                wait.AsyncWaitHandle.WaitOne();
                return state.sb.ToString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw new Exception("Some error occured" + e.Message);
            }
        }
        public static void AcceptCallback(IAsyncResult ar)
        {
            allDone.Set();
            if (ServerStarted == false) return;

            // Get the socket that handles the client request.
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = listener.EndAccept(ar);

            IPEndPoint remoteIpEndPoint = handler.RemoteEndPoint as IPEndPoint;

            Form1.lbStats.Invoke((MethodInvoker)(() =>
                    Form1.lbStats.Items.Add(string.Format("{0} (SERVER) Connection from {1}",
                    DateTime.Now, remoteIpEndPoint.Address))));
            Form1.lbStats.Invoke((MethodInvoker)(() => Form1.lbStats.TopIndex = Form1.lbStats.Items.Count - 1));

            // Create the state object.
            StateObject state = new StateObject();
            state.workSocket = handler;
            handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReadCallback), state);
        }
Пример #22
0
 void AcceptCallback(IAsyncResult ar) 
 { 
     try { 
         // Cast the user data back to a socket object 
         Socket s = ar.AsyncState as Socket; 
         // End the accept and get the resulting client socket 
         Socket s2 = s.EndAccept(ar); 
         // Keep the "Accept" process in motion 
         s.BeginAccept(acceptCallback, s); 
         // Create a state object for client (real apps may cache these) 
         StateObject state = new StateObject(); 
         state.workerSocket = s2; 
         // Start an async receive 
         state.workerSocket.BeginReceive(state.buffer, 0, state.buffer.Length, 0, receiveCallback, state); 
     } 
     catch(SocketException e) { 
         Debug.WriteLine(e.Message); 
         if(isLogging)
             TraceLog.myWriter.WriteLine( "SocketException:"+ e.Message+e.StackTrace,"AcceptCallback"); 
     } 
     return; // Return the thread to the pool 
 } // Async receive method + matching delegate variable 
        public static void Start()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            listener = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram, ProtocolType.Udp);

            listener.Bind(new IPEndPoint(IPAddress.Any, PORT));

            Console.WriteLine("Waiting for a connection...{0}", GetLocalIpAddress());

            while (true) {

                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                StateObject state = new StateObject();
                state.WorkSocket = listener;
                listener.ReceiveFrom(state.Buffer, ref remoteEndPoint);
                var rawMessage = Encoding.UTF8.GetString(state.Buffer);
                var messages = rawMessage.Split(';');

                if (messages.Length > 1) {
                    var command = messages[0];
                    var deviceName = messages[1];
                    Console.WriteLine("Command '{0}' is received from Device Name '{1}'", command, deviceName);
                    switch (command) {
                        case SocketCommands.CONNECT:
                            state.DeviceName = deviceName;
                            remoteEndpoints.Add(remoteEndPoint);
                            Send(rawMessage);
                            break;
                        default:
                            Send(rawMessage);
                            break;
                    }
                }
            }
        }
Пример #24
0
 public void setErrorMessage(Exception e, string errMsg)
 {
     StateObject stateObj = new StateObject(e);
     stateObj.SocMessage = errMsg;
     setErrorMessage(e, stateObj);
 }
Пример #25
0
 //initial receive function
 private void Recieve(StateObject state)
 {
     // Begin receiving the data from the remote device.
       Socket client = state.WorkSocket;
       client.BeginReceiveFrom(state.Buffer, 0, StateObject.BufferSize, 0, ref localEndPoint, new AsyncCallback(ReceiveCallback), state);
 }
Пример #26
0
 public void setErrorMessage(Exception e, StateObject obj)
 {
     obj.SocErrorMessage = e.Message;
     obj.Status = SocHandlerStatus.ERROR;
     Logger.error(obj);
     OnSocStatusChangedOnError(new SocStatusEventArgs(obj));
 }
Пример #27
0
        public int Send(Socket soc, byte[] buffer)
        {
            int retry = 0;
            int recv = 0;
            
            StateObject stateObj = new StateObject(soc);

            while (true)
            {
                try
                {
                    stateObj.Data = Encoding.UTF8.GetString(buffer, 8, buffer.Length - 8);
                    stateObj.Status = SocHandlerStatus.SENDING;
                    stateObj.SocMessage = string.Format("메시지전송 {0} Msg[{1}]", soc.RemoteEndPoint.ToString(), stateObj.Data);

                    recv = soc.Send(buffer, SocketFlags.None);
                    Logger.debug(stateObj);
                    OnSocStatusChangedOnDebug(new SocStatusEventArgs(stateObj));
                    if (recv == buffer.Length) break;
                }
                catch (ArgumentNullException ane)
                {
                    stateObj.SocMessage = string.Format("메시지전송에러:{0}", ane.ToString());
                    setErrorMessage(ane, stateObj);
                    return SocCode.SOC_ERR_CODE;
                }
                catch (SocketException se)
                {
                    stateObj.SocMessage = string.Format("메시지전송에러:{0}", se.ToString());
                    setErrorMessage(se, stateObj);
                    return SocCode.SOC_ERR_CODE;
                }
                catch (Exception e)
                {
                    stateObj.SocMessage = string.Format("메시지전송에러:{0}", e.ToString());
                    setErrorMessage(e, stateObj);
                    return SocCode.SOC_ERR_CODE;
                }

                if (retry >= 3)
                {
                    stateObj.SocMessage = String.Format("메시지전송에러:retry >= 3 " + Encoding.UTF8.GetString(buffer, 0, recv));
                    setErrorMessage(new Exception("메시지전송에러:retry >= 3"), stateObj);
                    return SocCode.SOC_ERR_CODE;
                }
                retry++;
            }
            return recv;
        }
Пример #28
0
 public int Send(IPEndPoint iep, string msg)
 {
     StateObject stateObj;
     lock(mClientTableLock) {
         if (mHtClientTable.ContainsKey(iep.ToString())) 
         {
             stateObj = mHtClientTable[iep.ToString()];
         } 
         else 
         {
             stateObj = new StateObject();
             stateObj.SocMessage = String.Format("{0} Send 대상연결이 없음 ", iep.ToString());
             OnSocStatusChanged(new SocStatusEventArgs(stateObj));
             return SocCode.SOC_ERR_CODE;
         }
     }
     return (Send(stateObj.Soc, SocUtils.GetPrefixInfo(msg)) - 8); //TEXT[msg length].... 8자리 감안
 }
Пример #29
0
 public int SendMsg(StateObject socObj)
 {
     return Send(socObj.Soc, socObj.Data);
 }
Пример #30
0
 public virtual void ProcessMsg(StateObject socObj)
 {
     //need implementing
 }