Laden...

empfangene Socket-Daten anzeigen

Erstellt von thepaul vor 17 Jahren Letzter Beitrag vor 17 Jahren 1.082 Views
T
thepaul Themenstarter:in
151 Beiträge seit 2005
vor 17 Jahren
empfangene Socket-Daten anzeigen

Hallo,

ich versuche gerade einen einfachen Client zu schreiben, der mit einem von mir geschriebenen Server kommuniziert.

Grundlegend dafür ist eine Klasse, die auf einem Socket aufbaut und Daten versenden und empfangen kann. Wenn Daten empfangen werden wird ein Event gefeuert.

Dieses wollte ich in einer WinForms-Anwendung abfangen. Allerdings wird die erhaltene Nachricht nicht angezeigt, sie wird aber vom Socket empfangen und das Event wird ebenfalls gefeuert.

Die AsyncSocket-Klasse


/// <remarks>
    /// AsyncSocket is the class that communicates with the server.
    /// </remarks>
    public class AsyncSocket 
    {
        private Socket _socket;
        private Decoder _decoder = Encoding.UTF8.GetDecoder();
        private UTF8Encoding _utf = new UTF8Encoding();
        private byte[] _buff = new byte[4096];
        private Stream _stream;


        /// <summary>
        /// Occurs when a connection is established with a server.
        /// </summary>
        public event EventHandler Connection;

        /// <summary>
        /// Occurs when a message has been received from the server.
        /// </summary>
        public event EventHandler<MessageEventArgs> Message;

        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncSocket"/> class.
        /// </summary>
        public AsyncSocket ()
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        /// <summary>
        /// Establishes a connection to the specified remote host.
        /// </summary>
        /// <param name="hostname">Hostname to connect to</param>
        /// <param name="ssl">Is this connection to be encrypted?</param>
        public void Connect(string hostname)
        {
            IPHostEntry ip = Dns.GetHostEntry(hostname);

             IPEndPoint ep = new IPEndPoint(ip.AddressList[0],5222);
            _socket.Connect(ep);
            if (_socket.Connected)
            {
                _stream = new NetworkStream(_socket);
            }
            _stream.BeginRead(_buff, 0, _buff.Length, new AsyncCallback(Receive), null);
            OnConnect();
        }

        /// <summary>
        /// Closes the current socket.
        /// </summary>
        public void Close()
        {
            _socket.Close();
        }

        /// <summary>
        /// Writes data to the current connection.
        /// </summary>
        /// <param name="msg">Message to send</param>
        public void Write(string msg)
        {
            byte[] mesg = _utf.GetBytes(msg);
            _stream.Write(mesg, 0, mesg.Length);
        }

        private void OnConnect()
        {
            if (Connection != null)
            {
                Connection(this, EventArgs.Empty);
            }
        }

        private void OnMessage(String message)
        {
            if (Message != null)
            {
                Message(this, new MessageEventArgs(message));
            }
        }

        private void Receive(IAsyncResult ar)
        {
            try
            {
                int rx = _stream.EndRead(ar);
                char[] chars = new char[rx];
                _decoder.GetChars(_buff, 0, rx, chars, 0);
                string msg = new string(chars);
                _stream.BeginRead(_buff, 0, _buff.Length, new AsyncCallback(Receive), null);
                OnMessage(msg);
            }
            catch (SocketException e)
            {
            }
            catch (InvalidOperationException e)
            {
            }
        }

        /// <summary>
        /// Gets the current status of the socket.
        /// </summary>
        public bool Connected
        {
            get { return _socket.Connected; }
        }
    }

Und das Formular:


public partial class TestForm : Form
    {
        AsyncSocket stream;

        public TestForm()
        {
            InitializeComponent();
            stream = new AsyncSocket();

            stream.Connection += new EventHandler(stream_Connection);
            stream.Message += new EventHandler<MessageEventArgs>(stream_Message);

            try
            {
                stream.Connect("127.0.0.1");
            }
            catch (Exception ex)
            {
                richTextBox1.AppendText(ex.Message+"\n");
                throw;
            }
        }

        void stream_Connection(object sender, EventArgs e)
        {
            button1.Enabled = true;
        }

        void stream_Message(object sender, MessageEventArgs e)
        {
            richTextBox1.AppendText(e.Message + "\n");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            stream.Write(textBox1.Text);
        }
    }
T
thepaul Themenstarter:in
151 Beiträge seit 2005
vor 17 Jahren

keine Ideen?

*push* 😉