Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Pedroalves

[Resolvido] problemas com sockets

Recommended Posts

com os socktes da me o seguinte erro Invole or BeginInvocke cannot be called on control util windows handle has been create

 

segue se o codigo na classe Logon.cs

 

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Client
{
   public partial class Logon : Form
   {
       public Logon()
       {
           InitializeComponent();
       }

       private void LoginBtnClick(object sender, EventArgs e)
       {
           if (String.IsNullOrWhiteSpace(usernameTxt.Text.Trim())) return;
           if (String.IsNullOrWhiteSpace(textBox1.Text.Trim())) return;
           Hide();

            MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=login");

            MySqlCommand cmd = new MySqlCommand("SELECT Tipo FROM user WHERE username  = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + textBox1.Text.Replace("'", "") + "' ");
           cmd.Connection = con;
           con.Open();
           object Tipo = cmd.ExecuteScalar();
           //MySqlDataReader reader=cmd.ExecuteReader();
           if (Tipo != null && Tipo != DBNull.Value)
           {
               if (Tipo.ToString() == "1")
               {
                   this.Dispose();

           new Client(usernameTxt.Text.Trim(), this).Show();
           //new Client(textBox1.Text.Trim(), this).Show();


               }
               else if (Tipo.ToString() == "2")
               {
                   MessageBox.Show("GAME MASTER");
               }
               else if (Tipo.ToString() == "3")
               {
                   MessageBox.Show("VIP");
               }
               else if (Tipo.ToString() == "4")
               {
                   MessageBox.Show("Membro");
               }
               else if (Tipo.ToString() == "5")
               {
                   MessageBox.Show("Registo nao foi Activado");
               }
               else if (Tipo.ToString() == "6")
               {
                   MessageBox.Show("O Utilizador foi banido\n Contacte atravez do suporte para saber a razão pelo qual foi banido(a)");
               }

           else
           {
               MessageBox.Show("Usuario ou Senha incorretos");


               }
       }
           }
       private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
       {
           if (e.KeyChar == (char)Keys.Enter)
               loginBtn.PerformClick(); //Perform Login button click if enter is pressed
       }

       internal static void Exit()
       {
           Application.Exit();
       }
   }
}

 

acho que o problema esta nesta classe

using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using Shared.Protocol;
using Shared.User;
using Shared.Messages;

namespace Server
{
   public class ClientHandler
   {
       #region Fields

       delegate void SendTextDelegate(string text);
       delegate void NewUserDelegate(User text, bool add);

       #endregion

       #region Properties

       Socket Socket { get; set; }
       BinaryWriter Writer { get; set; }
       BinaryReader Reader { get; set; }
       Server Instance { get; set; }
       public User User { get; set; }

       #endregion

       #region Constructors

       public ClientHandler(Socket socket, Server server)
       {
           Instance = server;
           Socket = socket;

           //Create a Network Stream for use in our Binary Writer and Reader
           var ns = new NetworkStream(socket);
           Writer = new BinaryWriter(ns);
           Reader = new BinaryReader(ns);
           User = new User("Unknown", Color.Black, Rank.Normal);
       }

       #endregion

       #region Methods

       public void HandleClient()
       {
           ProtocolObject packet;
           try
           {
               InvokeLog(@"A client has connected from " + IpAddress() + ".");

               while ((packet = Recieve()) != null)
               {
                   switch (packet.PacketType)
                   {
                       #region SendUser
                       case PacketType.SendUser:
                           {
                               User = (User) packet.Payload;
                               InvokeLog(@"User at " + IpAddress() + " is now known as " + User.Username);
                               InvokeUser(User, true);
                               break;
                           }
                           #endregion
                       #region SendUserList
                       case PacketType.SendUserList:
                           {
                               InvokeLog(@"Sending list of users to " + User.Username + " @ " + IpAddress());
                               var list = (from c in Instance.Clients where c.User.Username != User.Username select c.User).ToList();
                               Send(PacketType.RecieveUserList, list);
                           }
                           break;
                       #endregion
                       #region SendChatMessage
                       case PacketType.SendChatMessage:
                           {
                               var message = (Message) packet.Payload;
                               message.User = User;
                               InvokeLog(User.Username + " said: " + message.Text);

                               foreach (var c in Instance.Clients.Where(c => c.User.Username != User.Username))
                                   c.Send(PacketType.RecieveChatMessage, message);
                           }
                           break;
                       #endregion
                       #region ChangeUserColor
                       case PacketType.ChangeUserColor:
                           {
                               User.Color = (Color) packet.Payload;
                           }
                           break;
                       #endregion
                   }
               }
           }
           catch (Exception e)
           {
               Instance.Invoke(new SendTextDelegate(SendText), e.Message);
           }
           finally
           {
               DisconnectClient();
           }
       }

       public void DisconnectClient()
       {
           foreach (var l in 
               Instance.Clients.ToList().Where(c => c.User.Username == User.Username).Select(c => Instance.Clients.ToList().Where(ch => ch.User.Username != User.Username).ToList()))

               {
               Instance.Clients = l.ToList();

               Instance.Invoke(new SendTextDelegate(SendText), User.Username + " has disconnected from the server.");
               InvokeUser(User, false);
               User = null;
               Reader.Close();
               Writer.Close();
               Socket.Close();
           }
       }

       string IpAddress()
       {
           try { return Socket.RemoteEndPoint.ToString().Split(':')[0]; }
           catch (ObjectDisposedException) { return null; }
       }

       #endregion

       #region Send and Recieve

       ProtocolObject Recieve()
       {
           return DataProtocolObject.DeserializePacket(Reader);
       }

       public void Send(PacketType packetType, object payload)
       {
           DataProtocolObject.SerializePacket(Writer, new ProtocolObject(packetType, payload));
       }

       #endregion

       #region Delegates

       void InvokeLog(string text)
       {
           Instance.Invoke(new SendTextDelegate(SendText), text);
       }

       void SendText(string text)
       {
           Instance.AppendText(text);
       }

       void InvokeUser(User user, bool add)
       {
           Instance.Invoke(new NewUserDelegate(SendUser), user, add);
       }

       void SendUser(User user, bool add)
       {
           if (add)
           {
               if (Instance.Banned.UserExists(User))
               {
                   Send(PacketType.RecieveChatMessage, new Message("You have been Banned.", new User("Server", Color.Blue, Rank.Admin)));
                   DisconnectClient();
                   SendText("Banned user '" + user.Username + "' attempted to connect from: " + IpAddress());
                   return;
               }
               if (Instance.Admins.UserExists(User))
                   User.Rank = Rank.Admin;

               Instance.AddUserToList(User);
           }
           else
               Instance.RemoveUserFromList(User);
       }

       #endregion
   }
}

Compartilhar este post


Link para o post
Compartilhar em outros sites

using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Client
{
   public partial class Logon : Form
   {
       public Logon()
       {
           InitializeComponent();
       }

       private void LoginBtnClick(object sender, EventArgs e)
       {
           if (String.IsNullOrWhiteSpace(usernameTxt.Text.Trim())) return;
           if (String.IsNullOrWhiteSpace(textBox1.Text.Trim())) return;
           Hide();

            MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=login");

            MySqlCommand cmd = new MySqlCommand("SELECT Tipo FROM user WHERE username  = '" + usernameTxt.Text.Replace("'", "") + "' AND password = '" + textBox1.Text.Replace("'", "") + "' ");
           cmd.Connection = con;
           con.Open();
           object Tipo = cmd.ExecuteScalar();
           //MySqlDataReader reader=cmd.ExecuteReader();
           if (Tipo != null && Tipo != DBNull.Value)
           {
               if (Tipo.ToString() == "1")
               {


           new Client(usernameTxt.Text.Trim(), this).Show();
           //new Client(textBox1.Text.Trim(), this).Show();


               }
               else if (Tipo.ToString() == "2")
               {
                   MessageBox.Show("GAME MASTER");
               }
               else if (Tipo.ToString() == "3")
               {
                   MessageBox.Show("VIP");
               }
               else if (Tipo.ToString() == "4")
               {
                   MessageBox.Show("Membro");
               }
               else if (Tipo.ToString() == "5")
               {
                   MessageBox.Show("Registo nao foi Activado");
               }
               else if (Tipo.ToString() == "6")
               {
                   MessageBox.Show("O Utilizador foi banido\n Contacte atravez do suporte para saber a razão pelo qual foi banido(a)");
               }

           else
           {
               MessageBox.Show("Usuario ou Senha incorretos");


               }
       }
           }
       private void UsernameTxtKeyPress(object sender, KeyPressEventArgs e)
       {
           if (e.KeyChar == (char)Keys.Enter)
               loginBtn.PerformClick(); //Perform Login button click if enter is pressed
       }

       internal static void Exit()
       {
           Application.Exit();
       }
   }
}

o problema estava no this.dispose();

quando o tirei ficou a funcionar direito

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.