Почему я не могу получать сообщения с сервера чата? - PullRequest
0 голосов
/ 05 октября 2011

Почему я не могу получать сообщения с сервера чата?

Я разработал Chat Client в Visual Studio C # с моно для Android. Я хочу получать сообщения с сервера чата, который они отправляют, но он может быть получен клиентом чата, и я не могу показать их в Text1.Text

Исходный код клиента чата для приема сообщений:

  //Criado por EcoDuty, Frederico Vaz

  using System;
  using Android.App;
  using Android.Content;
  using Android.Runtime;
  using Android.Views;
  using Android.Widget;
  using Android.OS;

  //
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Text;
 using System.Net;
 using System.Net.Sockets;
 using System.IO;
 using System.Threading;
 using System.Runtime.InteropServices;

 namespace ChatClient_Android
{
[Activity(Label = "ChatClient_Android", MainLauncher = true, Icon = "@drawable/icon")]
public class MainChat : Activity
{

    public delegate void OnRecievedMessage(string message);

    public MainChat form;
    const int WM_VSCROLL = 0x115;
    const int SB_BOTTOM = 7;

    TextView text1;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        // Get our button from the layout resource,
        // and attach an event to it
        Button ligar = FindViewById<Button>(Resource.Id.btligar);
        text1 = FindViewById<TextView>(Resource.Id.text1);

      //Conexão com o servidor 
        ligar.Click += delegate
        {
            Connect();
            ligar.Enabled = false;

        };

    }

    //Função Actualizar a Caixa de Entrada de Mensagens 
    private void UpdateTextbox(string text)
    {
        text1.Text += "\r\n";
        text1.Text += text;
    }

    //Recieved Mesages
    public void RecievedMessage(string message)
    {
       UpdateTextbox(message);    
    }

   //TCP Connection
    public StreamWriter Outgoing;
    private StreamReader Incoming;
    private TcpClient Connection;
    private Thread Messages;
    private IPAddress IP;
    //public string host;
    //public string nick;
    //MainChat m_ParentForm;
    bool isConnected;

    //Função Conectar
    public void Connect()
    {
        try
        {
            IP = IPAddress.Parse("10.0.2.2");
            Connection = new TcpClient();
            Connection.Connect(IP, 1986);
            Outgoing = new StreamWriter(Connection.GetStream());
            Outgoing.WriteLine("EcoDuty");
            Outgoing.Flush();
            //m_ParentForm.Vis(true);
            Messages = new Thread(new ThreadStart(this.Communication));
            Messages.Start();
        }
        catch (Exception e) { Disconnected(e.Message); }
    }
    private void Communication()
    {
        Incoming = new StreamReader(Connection.GetStream());
        string check = Incoming.ReadLine();
        if (check[0] == '1')
        {
            //Vis(true);
            isConnected = true;
        }
        else
        {
            string Reason = "Disconnected: ";
            Reason += check.Substring(2, check.Length - 2);
            Disconnected(Reason);
            return;
        }
        while (isConnected == true)
        {
            try
            {
                ServerMessage(Incoming.ReadLine());
            }
            catch (Exception e)
            {
                if (isConnected == true)
                {
                    Disconnected("Connection to server lost");
                    Console.WriteLine("Connection Lost: " + e.ToString());
                }
                break;
            }
        }
    }
    private void ServerMessage(string message)
    {
        try
        {
            RecievedMessage(message);
        }
        catch { }
    }
    public void CloseConnection()
    {
        isConnected = false;
        Incoming.Close();
        Outgoing.Close();
        Connection.Close();
        Messages.Abort();
    }
    public void SendMessage(string message)
    {
        Outgoing.WriteLine(message);
        Outgoing.Flush();
    }



}

}

1 Ответ

1 голос
/ 05 октября 2011

Вы, похоже, пытаетесь обновить текст из потока, не являющегося пользовательским интерфейсом (если вы проследите за стеком вызовов, вы увидите, что метод вызывается из выделенного вами потока, который вы породили):

private void UpdateTextbox(string text)
{
    text1.Text += "\r\n";
    text1.Text += text;
}

Вместо этого используйте RunOnUiThread(), чтобы запланировать изменение текста для выполнения в потоке пользовательского интерфейса:

private void UpdateTextbox(string text)
{
    RunOnUiThread(() =>
    {
      text1.Text += "\r\n";
      text1.Text += text;
    });
}

Также вы должны избавиться от пустого исключения, которое вы делаете по пути - это, скорее всего, скрыло проблему.

Кроме того, всегда проверяйте catlog на наличие исключений, они обычно являются хорошим индикатором.

...