Einzelnen Beitrag anzeigen

TurboMartin

Registriert seit: 13. Feb 2006
Ort: Bad Honnef
765 Beiträge
 
Turbo Delphi für Win32
 
#4

Re: [C#/.NET] Client-Listener möglich?

  Alt 1. Mai 2010, 10:52
Code:
    public class AsyncObject
    {
        public bool Connected = false; // ID received flag
        public Socket Socket = null; // Client socket.
        public const int BufferSize = 1024; // Size of receive buffer.
        public byte[] Buffer = new byte[BufferSize];// Receive buffer.
        public List<byte> Received = new List<byte>();
    }
Code:
        protected void ReadCallback(IAsyncResult ar)
        {
            String content = String.Empty;

            AsyncObject state = (AsyncObject)ar.AsyncState;
            Socket handlersocket = state.Socket;
            try
            {
                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);

                if (bytesRead > 0)
                {
                    state.Received.AddRange(state.Buffer);
                    content = B2S(state.Buffer);
                    if ((content.Length > 0) && content.Contains(ENDKOMMANDO))
                    {
                        HandleMessages(state, state.Received);
                    }
                    else
                    {
                        // Nicht alle Daten wurden empfangen
                        handlersocket.BeginReceive(state.Buffer, 0, AsyncObject.BufferSize, 0, new AsyncCallback(this.ReadCallback), state);
                    }
                }
                else
                {
                    // Disconnected
                }
            }
            catch (System.Net.Sockets.SocketException es)
            {
                if (es.ErrorCode != 64)
                {
                    Console.WriteLine(string.Format("Socket Exception: {0}, {1}.", es.ErrorCode, es.ToString()));
                }
            }
            catch (Exception e)
            {
                if (e.GetType().FullName != "System.ObjectDisposedException")
                {
                    Console.WriteLine(string.Format("Exception: {0}.", e.ToString()));
                }
            }
        }
Code:
AsyncObject state = new AsyncObject();
state.Socket = tcp.Client;
tcp.Client.BeginReceive(state.Buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(this.ReadCallback), state);
Tomorrow will be cancelled due to lack of interest.

  Mit Zitat antworten Zitat