Jump to content

  • Log In with Google      Sign In   
  • Create Account

create a connection client


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
14 replies to this topic

#1 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 23 August 2012 - 07:40 PM

i can create a connection to the server with neoforce project this is the code
the problem when the user make login with sucess add the user to the server
the same code with form works fine with neoforce i have this errors and when the user send a text in send a name of the user and not a time
Error 4 The name 'Invoke' does not exist in the current context C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 161 13 Central
Error 1 'TomShane.Neoforce.Controls.Layout': static types cannot be used as return types C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 38 24 Central
Error 2 'TomShane.Neoforce.Controls.Layout': static types cannot be used as parameters C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 38 29 Central
Error 3 'TomShane.Neoforce.Controls.Layout': static types cannot be used as parameters C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 41 17 Central
Error 5 'TomShane.Neoforce.Controls.Layout' does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'TomShane.Neoforce.Controls.Layout' could be found (are you missing a using directive or an assembly reference?) C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 171 21 Central
Error 6 'TomShane.Neoforce.Controls.Layout' does not contain a definition for 'Invoke' and no extension method 'Invoke' accepting a first argument of type 'TomShane.Neoforce.Controls.Layout' could be found (are you missing a using directive or an assembly reference?) C:\Users\Alves\Dropbox\Jogos\TomShane.Neoforce.Controls.XNA4\Neoforce\Source\Central\Code\World.cs 181 21 Central
class world.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using TomShane.Neoforce.Controls;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Shared.Protocol;
using Shared.User;
using Message = Shared.Messages.Message;
using System.Windows.Forms;
using FableServer;
using TomShane.Neoforce.Central;

namespace TomShane.Neoforce.Central
{
    public sealed partial class World : Window
    {
	    #region Fields
	    const int Port = 50143;
	    delegate void SendTextDelegate(Message message);
	    delegate void AddUserDelegate(User user);
	    delegate void ClearUserListDelegate();
	    #endregion
	    #region Properties
	    User User { get; set; }
	    TcpClient TcpClient { get; set; }
	    BinaryWriter Writer { get; set; }
	    BinaryReader Reader { get; set; }
	 Layout Instance { get; set; }
	    #endregion
	   
	    public  World(Manager manager,string text, Layout instance): base(manager)
	    {
		 User = new User(text, System.Drawing.Color.Black, Rank.Normal);
		  Instance = instance;
		    SetupClient();
		  
		    InitConsole();
		   
    }
	   
	
	    void SetupClient()
	    {
		    try
		    {
			    TcpClient = new TcpClient("localhost", Port);
			    Writer = new BinaryWriter(new NetworkStream(TcpClient.Client));
			    Reader = new BinaryReader(new NetworkStream(TcpClient.Client));
			    ThreadStart ts = delegate
			    {
				    HandleServer();
				    Close();
			    };
			    var t = new Thread(ts);
			    t.Start();
			    //Setup Username and send it to server
			  //  new Message("Ola: " + User.Username, new User("Server", Color.Yellow, Rank.Admin));
			    Send(PacketType.SendUser, User);
			    GetUserList();
		    }
		    catch (Exception e)
		    {
			    TomShane.Neoforce.Controls.MessageBox.Show(Manager, TomShane.Neoforce.Controls.MessageBox.MessageBoxType.CANCEL, "ERRO"+e, "");
			    CloseServer();
		    }
	    }
	    #region Methods

	    void GetUserList()
	    {
		    //Get list of users on the server
		    //AppendText(new Message("WELCOME TO ", new User("Server", Color.Gold, Rank.Admin)));
		   // AppendText(new Message("WELCOME TO SERVER: " + User.Username + "", new User("Server", Color.Gold, Rank.Admin)));
		    Send(PacketType.SendUserList, null);
	    }
	    void CloseServer()
	    {
		    if (Writer != null) Writer.Close();
		    if (Reader != null) Reader.Close();
		    if (TcpClient != null) TcpClient.Close();
		    //Logon.Exit();
	    }
	    void HandleServer()
	    {
		    try
		    {
			    ProtocolObject packet;
			    while ((packet = Recieve()) != null)
			    {
				    switch (packet.PacketType)
				    {
					    #region RecieveChatMessage
					    case PacketType.RecieveChatMessage:
						    {
							    InvokeLog((Message)packet.Payload);
						    }
						    break;
					    #endregion
					    #region RecieveUserList
					    case PacketType.RecieveUserList:
						    {
							    InvokeUserList();
							    foreach (var l in (List<User>)packet.Payload)
								    InvokeUser(l);
						    }
						    break;
					    #endregion
				    }
			    }
		    }
		    catch (Exception e)
		    {
			    TomShane.Neoforce.Controls.MessageBox.Show(Manager, TomShane.Neoforce.Controls.MessageBox.MessageBoxType.CANCEL, "ERRO"+e, "");
			    CloseServer();
		    }
	    }
	  
	   void Title(Message message)
	    {
		    AppendText(message);
		   Text = message.Text == null ? @"Client" : @"Client - " + message.Text;
	   }
	    #endregion
	    #region Send and Recieve
	    void Send(PacketType packetType, object payload)
	    {
		    DataProtocolObject.SerializePacket(Writer, new ProtocolObject(packetType, payload));
	    }
	    ProtocolObject Recieve()
	    {
		    return DataProtocolObject.DeserializePacket(Reader);
	    }
	    #endregion
	    #region Delegates
	   void InvokeLog(Message message)
	    {
		    Invoke(new SendTextDelegate(SendText), message);
	    }
	    void SendText(Message message)
	    {
		   AppendText(message);
	    }
	    void InvokeUser(User user)
	    {
		   Instance.Invoke(new AddUserDelegate(AddUser), user);
	    }
	   
	    void AddUser(User user)
	    {
	   //    AddUserToList(user);
	    }
	    void InvokeUserList()
	    {
		   Instance.Invoke(new ClearUserListDelegate(ClearUsers));
	    }
	    void ClearUsers()
	    {
		  //    userList.Items.Clear();
	    }
	    #endregion
	 void AppendText(Message message)
	    {
		    //con1.SelectionColor = message.User.Color;
		    //con1.AppendText(Environment.NewLine + message.User.Username + ": " + message.Text);
	    }
	 
	    #region Console
	    private void InitConsole()
    {
	  TomShane.Neoforce.Controls.TabControl tbc = new TomShane.Neoforce.Controls.TabControl(Manager);
	  TomShane.Neoforce.Controls.Console con1 = new TomShane.Neoforce.Controls.Console(Manager);
	  TomShane.Neoforce.Controls.Console con2 = new TomShane.Neoforce.Controls.Console(Manager);
	  //Console con3 = new Console(Manager);
	 
	  // Setup of TabControl, which will be holding both consoles
	  tbc.Init();
	  tbc.AddPage("Global");
	  tbc.AddPage("Guild");
	  tbc.AddPage("PARTY");
	  tbc.AddPage("TRADE");
	  tbc.Alpha = 220;
	  tbc.Left = 220;
	  tbc.Height = 220;
	  tbc.Width = 400;
	  tbc.Top = Manager.TargetHeight - tbc.Height - 32;	 
	 
	  tbc.Movable = true;
	  tbc.Resizable = true;
	  tbc.MinimumHeight = 96;
	  tbc.MinimumWidth = 160;  
					  
	  tbc.TabPages[0].Add(con1);
	  tbc.TabPages[1].Add(con2);
	  //tbc.TabPages[2].Add(con3);
							 
	  con1.Init();
	  con2.Init();
	  //con3.Init();
	  con2.Width = con1.Width = tbc.TabPages[0].ClientWidth;
	  con2.Height = con1.Height = tbc.TabPages[0].ClientHeight;
	  con2.Anchor = con1.Anchor = Anchors.All;			   
	  con1.Channels.Add(new ConsoleChannel(0, "General", Color.Orange));
	  con1.Channels.Add(new ConsoleChannel(1, "Private", Color.White));
	  con1.Channels.Add(new ConsoleChannel(2, "System", Color.Yellow));
	  con1.Channels.Add(new ConsoleChannel(3, "Guild", Color.Green)); 
	 
	  // We want to share channels and message buffer in both consoles
	  con2.Channels = con1.Channels;
	  con2.MessageBuffer = con1.MessageBuffer;					  
	 
	  // In the second console we display only "Private" messages
	  con2.ChannelFilter.Add(3);		   
	 
	  // Select default channels for each tab
	  con1.SelectedChannel = 0;
	  con2.SelectedChannel = 3;
	  //con3.SelectedChannel = 3;
	 
	  // Do we want to add timestamp or channel name at the start of every message?
	  con1.MessageFormat = ConsoleMessageFormats.All;
	  con2.MessageFormat = ConsoleMessageFormats.TimeStamp;
	  // Handler for altering incoming message
	  con1.MessageSent += new ConsoleMessageEventHandler(con1_MessageSent);	 
	 
	  // We send initial welcome message to System channel
	  con1.MessageBuffer.Add(new ConsoleMessage("WELCOME TO THE SERVER!",2));
				   
	  Manager.Add(tbc);	 
    }
    ////////////////////////////////////////////////////////////////////////////
   
    ////////////////////////////////////////////////////////////////////////////
    void con1_MessageSent(object sender, ConsoleMessageEventArgs e)
    {
	  if (e.Message.Channel == 0)
	  {
	    //e.Message.Text = "(!) " + e.Message.Text;
	  }
    }
    ////////////////////////////////////////////////////////////////////////////
	  
    #endregion
  
  }
    }

class logic.cs
void btnApply_Click(object sender, Controls.EventArgs e)
    {
		   String user = txusername.Text.Trim();
	    System.Console.WriteLine(user);
	    String userPassword = txpassword.Text.Trim();
	    System.Console.WriteLine(userPassword);
	    try
	    {
	   
		    MySqlConnection con = new MySqlConnection("host=localhost;user=root;database=jogo");
		    MySqlCommand cmd = new MySqlCommand("SELECT password FROM w70tg_users WHERE username  ='" + user + "'");
		    cmd.Connection = con;
		    con.Open();
		    object hello = cmd.ExecuteScalar();
		    if (hello == null)
		    {
			    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL, "ERRO", "");
		    }
		    else
		    {
			    string password = hello.ToString();
				 // que hizo el usuario escribe?			   
			    con.Close();
			    if (Check(userPassword, password))
			    {
				    // corregir!
				    MySqlCommand cmdo = new MySqlCommand("SELECT w70tg_user_usergroup_map.group_id FROM w70tg_users INNER JOIN w70tg_user_usergroup_map on w70tg_user_usergroup_map.user_id=w70tg_users.id  WHERE username  = '" +  txusername.Text + "'");
				    cmdo.Connection = con;
				    con.Open();
				    object Tipo = cmdo.ExecuteScalar();
				    if (Tipo != null && Tipo != DBNull.Value)
				    {
					    switch (System.Convert.ToInt32(Tipo))
					    {
						    case 8:
							    // serverselection ola = new serverselection();
							    // ola.Show();
							   // Hide();
							    World ola = new World(Manager);
							  
				 ola.Init();
		   
		    ola.Width = 300;
		    ola.Height = 225;
		    ola.Center();
		    ola.Visible = true;
		    txusername.Hide();
		    txpassword.Hide();
		    lbusername.Hide();
		    lbpassword.Hide();
		    btnApply.Hide();
		    btnExit.Hide();
		    ola.CloseButtonVisible = false;
		 
							    break;
						    case 11:
							   MessageBox.Show( Manager,MessageBox.MessageBoxType.CANCEL,"GAME MASTER","");
							    break;
						    case 10:
							    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL, "Moderador","");
							    break;
						    case 3:
							    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL, "VIP", "");
							    break;
						    case 2:
							    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL, "Membro", "");
							    break;
						    case 1:
							    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL, "O Utilizador foi banido\n Contacte a Equipa atravez do suporte para saber a razão pelo qual foi banido(a)","");
							    break;
					    }
				    }
			    }
			    else
			    {
				 
				    txpassword.Text = null;
				    txusername.Text = null;
			    }
			    con.Close();
		    }
	    }
	    catch (MySqlException msqle)
	    {
		    MessageBox.Show(Manager, MessageBox.MessageBoxType.CANCEL,"ERRO"+msqle.Message, "");
	    }

	 }


Sponsor:

#2 rip-off   Moderators   -  Reputation: 8713

Like
0Likes
Like

Posted 24 August 2012 - 10:27 AM

Since the question appears to be only incidentally concerning networking, I have moved it to general programming.

#3 hplus0603   Moderators   -  Reputation: 5693

Like
0Likes
Like

Posted 24 August 2012 - 10:31 AM

static types cannot be used as return types


This is a C# error message about the code syntax.
It looks like the "Neoforce" library is not designed to work in the environment you're trying to use it.
enum Bool { True, False, FileNotFound };

#4 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 24 August 2012 - 12:52 PM

i want connect the neoforce project to my server but i can´t
how i put the neoforce library work with tcp

#5 Landi20   Members   -  Reputation: 214

Like
-1Likes
Like

Posted 26 August 2012 - 04:21 PM

how i solve my problem
someone can help me

#6 rip-off   Moderators   -  Reputation: 8713

Like
2Likes
Like

Posted 27 August 2012 - 04:35 AM

The errors you are getting point to fundamental weaknesses in your current understanding of the language. This indicates that your chosen project is well above the level of your abilities at this time. This is the programming equivalent of trying to run before you can walk.

I would recommend you put this project on hold for the time being, and go back to learning the core language. Buy a good book, or borrow one from your local library, and go through it, paying particular attention to completing all the exercises at the end of each chapter.

Once you've built up your skills, then you can try to tackle a few small games first. Building games like this will get your learning about how to design larger and larger programs, which is another skill that you'll need. Designing a simple game like Pong is quite different from something like Mario or Doom.

I wouldn't recommend trying a networked game as one of your first few projects, there are a lot of skills you will need to be able to make such a game. Your first networked program should probably be something like a chat client or a simple HTTP server, something to familiarise yourself with the concepts and how to debug issues.

This is true for all technologies. If you aren't comfortable using a database make a separate project to get familiar - for example implement some simple DVD or Book cataloguing software. If you have never made a game using Neoforce then write something small using it to ensure you understand what it gives you and how to use it.

Finally, when you've built up your core language skills, your project design skills and your skills in the specific technologies you want to use, then return to your current project.

#7 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 27 August 2012 - 07:21 AM

making network connection with form i can make but with neoforce not
becouse the mettod invoke don´t exist in neoforce project
that is my problem

#8 rip-off   Moderators   -  Reputation: 8713

Like
2Likes
Like

Posted 27 August 2012 - 12:40 PM

I understand your problem. The code will not be the same in both cases. The fact that you appear to expect it to be, and the level of technical detail in your reply indicates you have not yet got all the necessary skills I have been talking about.

If you have been copying code from tutorials, be aware that this can make you appear to be able to do more than you actually can. Part of learning a new skill is understanding how much or little one knows - the ability to making accurate introspective judgements. In my experience as a developer, and as someone who has seen people at all levels of skill here on gamedev.net, I am fairly certain of my evaluation of your current ability.

If you can tell me what you have tried in enough detail to prove my evaluation wrong (for example, perhaps the language barrier is interfering with my perception), I will certainly try to help you. But I can not meaningfully help you with this specific problem right now, because the real cause of this problem is you being out of your depth.

#9 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 27 August 2012 - 01:57 PM

what is the name dll file is responsible for the method of invoke
if a add this file to my references maybe solve my problem

Edited by Landi20, 28 August 2012 - 09:27 AM.


#10 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 31 August 2012 - 10:21 AM

finally i solve the problem
class in the world and where we will spend the whole game ie where are the monsters, npc players and even my divuda is if I have to pass this code to xna or simply can stay like this

#11 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 02 September 2012 - 01:34 PM

someone can help me

#12 rip-off   Moderators   -  Reputation: 8713

Like
0Likes
Like

Posted 03 September 2012 - 03:14 AM

Your previous post seems to indicate you have solved the problem, so it isn't clear what help you now require. Can you elaborate on your current issue? If there is an error, post it. If the problem is with the runtime behaviour, can you explain what you are actually seeing versus what you expect to see?

If possible, post a minimal code example that demonstrates the error or behaviour. Try to isolate the problem from the rest of your code.

#13 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 03 September 2012 - 07:25 AM

i have the login and world like this public sealed partial class World : Window
i my question is the world can be public sealed partial class World : Window your have to be a game component
if yes you pass the windows to a game component

#14 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 25 July 2013 - 01:23 PM

i make some changes in my server but i can´t recive the username and the password

this is the code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

namespace RelayServer
{
    public class Client
    {
        //Encapsulated 
        private TcpClient client;

        //Byte array that is populated when a user receives data
        private byte[] readBuffer;

        //Create the events
        public event ConnectionEvent UserDisconnected;
        public event DataReceivedEvent DataReceived;

        //The ID of this client, the constructor is only allowed to set this variable
        public readonly byte id;

        //IP of the connected client
        public string IP;
	public string username;
	public string password;

        //Is this client disconnected?
        bool connected = false;

        /// <summary>
        /// Create a new client
        /// </summary>
        /// <param name="client">TcpClient object to use</param>
        /// <param name="id">ID to give to the client</param>
        public Client(TcpClient client, byte id)
        {
            readBuffer = new byte[Properties.Settings.Default.ReadBufferSize];
            this.id = id;
            this.client = client;
            IP = client.Client.RemoteEndPoint.ToString();
            client.NoDelay = true;

            StartListening();
            connected = true;
        }

        /// <summary>
        /// Create an empty Client object
        /// </summary>
        /// <param name="ip">IP to give to the client</param>
        /// <param name="port">Port to connect</param>
        public Client(string ip, int port,string username,string password)
        {
            readBuffer = new byte[Properties.Settings.Default.ReadBufferSize];
            id = byte.MaxValue;
            client = new TcpClient();
            client.NoDelay = true;
            client.Connect(ip, port,username,password);

            StartListening();
            connected = true;
        }

        /// <summary>
        /// Disconnect the client from the server
        /// </summary>
        public void Disconnect()
        {
            if (connected)
            {
                connected = false;
                client.Close();

                //Call all delegates
                if (UserDisconnected != null)
                    UserDisconnected(this, this);
            }
        }

        /// <summary>
        /// Start listening for new data
        /// </summary>
        private void StartListening()
        {
            client.GetStream().BeginRead(readBuffer, 0, Properties.Settings.Default.ReadBufferSize, StreamReceived, null);
        }

        /// <summary>
        /// Data was received
        /// </summary>
        /// <param name="ar">Async status</param>
        private void StreamReceived(IAsyncResult ar)
        {
            int bytesRead = 0;
            try
            {
                lock (client.GetStream())
                {
                    bytesRead = client.GetStream().EndRead(ar);
                }
            }

            catch (Exception e) { }

            //An error happened that created bad data
            if (bytesRead == 0)
            {
                Disconnect();
                Console.WriteLine("Client {0}:  {1}\n{2}", IP, "Bad data", "Disconnecting");
                return;
            }

            //Create the byte array with the number of bytes read
            byte[] data = new byte[bytesRead];

            //Populate the array
            for (int i = 0; i < bytesRead; i++)
                data[i] = readBuffer[i];

            //Listen for new data
            StartListening();

            //Call all delegates
            if (DataReceived != null)
                DataReceived(this, data);
        }

        /// <summary>
        /// Code to actually send the data to the client
        /// </summary>
        /// <param name="b">Data to send</param>
        public void SendData(byte[] b)
        {
            //Try to send the data.  If an exception is thrown, disconnect the client
            try
            {
                lock (client.GetStream())
                {
                    client.GetStream().BeginWrite(b, 0, b.Length, null, null);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Client {0}:  {1}", IP, e.ToString());
            }
        }

        /// <summary>
        /// Code to send data in a MemoryStream format
        /// </summary>
        /// <param name="ms">The data to send</param>
        public void SendMemoryStream(System.IO.MemoryStream ms)
        {
            lock (ms)
            {
                int bytesWritten = (int)ms.Position;
                byte[] result = new byte[bytesWritten];

                ms.Position = 0;
                ms.Read(result, 0, bytesWritten);
                SendData(result);
            }
        }

        /// <summary>
        /// String representation of the Client
        /// </summary>
        /// <returns>IP address</returns>
        public override string ToString()
        {
            return IP;
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RelayServer
{
    public delegate void ConnectionEvent(object sender, Client user);
    public delegate void DataReceivedEvent(Client sender, byte[] data);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace RelayServer
{
    public class Listener
    {
        private TcpListener listener;

        //send an even once we receive a user
        public event ConnectionEvent userAdded;


        //a variable to keep track of how many users we've added
        private bool[] usedUserID;

        /// <summary>
        /// Create a new Listener object
        /// </summary>
        /// <param name="portNr">Port to use</param>
        public Listener(int portNr)
        {
            //Create an array to hold the used IDs
            usedUserID = new bool[Properties.Settings.Default.MaxNumberOfClients];

            //Create the internal TcpListener
            listener = new TcpListener(IPAddress.Any, portNr);
        }

        /// <summary>
        /// Starts a new session of listening for messages.
        /// </summary>
        public void Start()
        {
            listener.Start();
            ListenForNewClient();
        }

        /// <summary>
        /// Stops listening for messages.
        /// </summary>
        public void Stop()
        {
            listener.Stop();
        }

        /// <summary>
        /// Used for allowing new users to connect
        /// </summary>
        private void ListenForNewClient()
        {
            listener.BeginAcceptTcpClient(AcceptClient, null);
        }

        /// <summary>
        /// Called when a client connects to the server
        /// </summary>
        /// <param name="ar">Status of the Async method</param>
        private void AcceptClient(IAsyncResult ar)
        {
            //We need to end the Async method of accepting new clients
            TcpClient client = listener.EndAcceptTcpClient(ar);

            //id is originally -1 which means a user cannot connect
            int id = -1;
            for (byte i = 0; i < usedUserID.Length; i++)
            {
                if (usedUserID[i] == false)
                {
                    id = i;
                    break;
                }
            }

            //If the id is still -1, the client what wants to connect cannot (probably because we have reached the maximum number of clients
            if (id == -1)
            {
                Console.WriteLine("Client " + client.Client.RemoteEndPoint.ToString() + " cannot connect. ");
                return;
            }

            //ID is valid, so create a new Client object with the server ID and IP
            usedUserID[id] = true;
            Client newClient = new Client(client, (byte)id);

            //We are now connected, so we need to set up the User Disconnected event for this user.
            newClient.UserDisconnected += new ConnectionEvent(client_UserDisconnected);

            //We are now connected, so call all delegates of the UserAdded event.
            if (userAdded != null)
                userAdded(this, newClient);

            //Begin listening for new clients
            ListenForNewClient();
        }

        /// <summary>
        /// User disconnects from the server
        /// </summary>
        /// <param name="sender">Original object that called this method</param>
        /// <param name="user">Client to disconnect</param>
        void client_UserDisconnected(object sender, Client user)
        {
            usedUserID[user.id] = false;
        }

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace RelayServer
{
    public class Server
    {
        //Singleton in case we need to access this object without a reference (call <Class_Name>.singleton)
        public static Server singleton;

        //Create an object of the Listener class.
        Listener listener;
        public Listener Listener
        {
            get { return listener; }
        }

        //Array of clients
        Client[] client;

        //number of connected clients
        int connectedClients = 0;

        //Writers and readers to manipulate data
        MemoryStream readStream;
        MemoryStream writeStream;
        BinaryReader reader;
        BinaryWriter writer;

        /// <summary>
        /// Create a new Server object
        /// </summary>
        /// <param name="port">The port you want to use</param>
        public Server(int port)
        {
            //Initialize the array with a maximum of the MaxClients from the config file.
            client = new Client[Properties.Settings.Default.MaxNumberOfClients];

            //Create a new Listener object
            listener = new Listener(port);
            listener.userAdded += new ConnectionEvent(listener_userAdded);
            listener.Start();

            //Create the readers and writers.
            readStream = new MemoryStream();
            writeStream = new MemoryStream();
            reader = new BinaryReader(readStream);
            writer = new BinaryWriter(writeStream);

            //Set the singleton to the current object
            Server.singleton = this;
        }

        /// <summary>
        /// Method that is performed when a new user is added.
        /// </summary>
        /// <param name="sender">The object that sent this message</param>
        /// <param name="user">The user that needs to be added</param>
        private void listener_userAdded(object sender, Client user)
        {
            connectedClients++;

            //Send a message to every other client notifying them on a new client, if the setting is set to True
            if (Properties.Settings.Default.SendMessageToClientsWhenAUserIsAdded)
            {
                writeStream.Position = 0;

                //Write in the form {Protocol}{User_ID}{User_IP}
                writer.Write(Properties.Settings.Default.NewPlayerByteProtocol);
                writer.Write(user.id);
                writer.Write(user.IP);

                SendData(GetDataFromMemoryStream(writeStream), user);
            }

            //Set up the events
            user.DataReceived += new DataReceivedEvent(user_DataReceived);
            user.UserDisconnected += new ConnectionEvent(user_UserDisconnected);

            //Print the new player message to the server window.
            Console.WriteLine(user.ToString() + " connected\tConnected Clients:  " + connectedClients + "\n");

            //Add to the client array
            client[user.id] = user;
        }

        /// <summary>
        /// Method that is performed when a new user is disconnected.
        /// </summary>
        /// <param name="sender">The object that sent this message</param>
        /// <param name="user">The user that needs to be disconnected</param>
        private void user_UserDisconnected(object sender, Client user)
        {
            connectedClients--;

            //Send a message to every other client notifying them on a removed client, if the setting is set to True
            if (Properties.Settings.Default.SendMessageToClientsWhenAUserIsRemoved)
            {
                writeStream.Position = 0;

                //Write in the form {Protocol}{User_ID}{User_IP}
                writer.Write(Properties.Settings.Default.DisconnectedPlayerByteProtocol);
                writer.Write(user.id);
                writer.Write(user.IP);

                SendData(GetDataFromMemoryStream(writeStream), user);
            }

            //Print the removed player message to the server window.
            Console.WriteLine(user.ToString() + " disconnected\tConnected Clients:  " + connectedClients + "\n");

            //Clear the array's index
            client[user.id] = null;
        }

        /// <summary>
        /// Relay messages sent from one client and send them to others
        /// </summary>
        /// <param name="sender">The object that called this method</param>
        /// <param name="data">The data to relay</param>
        private void user_DataReceived(Client sender, byte[] data)
        {
            writeStream.Position = 0;

            if (Properties.Settings.Default.EnableSendingIPAndIDWithEveryMessage)
            {
                //Append the id and IP of the original sender to the message, and combine the two data sets.
                writer.Write(sender.id);
                writer.Write(sender.IP);
                data = CombineData(data, writeStream);
            }

            //If we want the original sender to receive the same message it sent, we call a different method
            if (Properties.Settings.Default.SendBackToOriginalClient)
            {                
                SendData(data);
            }
            else
            {
                SendData(data, sender);
            }
        }

        /// <summary>
        /// Converts a MemoryStream to a byte array
        /// </summary>
        /// <param name="ms">MemoryStream to convert</param>
        /// <returns>Byte array representation of the data</returns>
        private byte[] GetDataFromMemoryStream(MemoryStream ms)
        {
            byte[] result;

            //Async method called this, so lets lock the object to make sure other threads/async calls need to wait to use it.
            lock (ms)
            {
                int bytesWritten = (int)ms.Position;
                result = new byte[bytesWritten];

                ms.Position = 0;
                ms.Read(result, 0, bytesWritten);
            }

            return result;
        }

        /// <summary>
        /// Combines one byte array with a MemoryStream
        /// </summary>
        /// <param name="data">Original Message in byte array format</param>
        /// <param name="ms">Message to append to the original message in MemoryStream format</param>
        /// <returns>Combined data in byte array format</returns>
        private byte[] CombineData(byte[] data, MemoryStream ms)
        {
            //Get the byte array from the MemoryStream
            byte[] result = GetDataFromMemoryStream(ms);

            //Create a new array with a size that fits both arrays
            byte[] combinedData = new byte[data.Length + result.Length];

            //Add the original array at the start of the new array
            for (int i = 0; i < data.Length; i++)
            {
                combinedData[i] = data[i];
            }

            //Append the new message at the end of the new array
            for (int j = data.Length; j < data.Length + result.Length; j++)
            {
                combinedData[j] = result[j - data.Length];
            }

            //Return the combined data
            return combinedData;
        }

        /// <summary>
        /// Sends a message to every client except the source.
        /// </summary>
        /// <param name="data">Data to send</param>
        /// <param name="sender">Client that should not receive the message</param>
        private void SendData(byte[] data, Client sender)
        {
            foreach (Client c in client)
            {
                if (c != null && c != sender)
                {
                    c.SendData(data);
                }
            }

            //Reset the writestream's position
            writeStream.Position = 0;
        }

        /// <summary>
        /// Sends data to all clients
        /// </summary>
        /// <param name="data">Data to send</param>
        private void SendData(byte[] data)
        {
            foreach (Client c in client)
            {
                if(c != null)
                    c.SendData(data);
            }

            //Reset the writestream's position
            writeStream.Position = 0;
        }
    }
}

can someone can help-me


Edited by Landi20, 27 July 2013 - 09:52 AM.


#15 Landi20   Members   -  Reputation: 214

Like
0Likes
Like

Posted 29 July 2013 - 11:26 PM

i find the solution

i have create a new cliente and  server to make it work


Edited by Landi20, 03 August 2013 - 04:41 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS