Exemple #1
0
        /// <summary>
        /// The actions that should be performed when connecting
        /// </summary>
        private void ClickConnect()
        {
            // Pass the name to the network controller
            gState = Client.Connect_to_Server(ConnectCallBack, ServerBox.Text);

            // Make GUI elements invisible
            ServerBox.Visible     = false;
            ServerBox.Enabled     = false;
            PlayerBox.Visible     = false;
            PlayerBox.Enabled     = false;
            ServerLabel.Visible   = false;
            PlayerLabel.Visible   = false;
            ConnectButton.Visible = false;
            ConnectButton.Enabled = false;
            TitleLabel.Visible    = false;
            TitleLabel.Enabled    = false;

            // Make game stats visible
            FPSLabel.Visible   = true;
            FPSValue.Visible   = true;
            FoodLabel.Visible  = true;
            FoodValue.Visible  = true;
            MassLabel.Visible  = true;
            MassValue.Visible  = true;
            WidthLabel.Visible = true;
            WidthValue.Visible = true;

            // We should start painting the cubes
            paintIt = true;

            // Connect has been clicked
            connectClicked = true;
        }
Exemple #2
0
 /// <summary>
 /// Callback that sends our name to the server
 /// </summary>
 /// <param name="state"></param>
 public void First_Contact_Callback(PreservedState state)
 {
     pstate = state;
     NetworkingCode.Send(pstate.State_Socket, Name_Textbox.Text + "\n");
     state.State_Callback = Received_Player_Callback;
     NetworkingCode.i_want_more_data(state);
 }
Exemple #3
0
        /// <summary>
        /// Updates the world with all the new cubes from the json
        /// </summary>
        /// <param name="state"> The state object of the network controller</param>
        public void UpdateWorld(PreservedState state)
        {
            // If there's a serer error, set serverError to true
            if (state.error)
            {
                serverError = true;
            }
            // If no error, update the world with the json in the state's stringbuilder
            else
            {
                string stringbuilder = (state.sb).ToString();

                List <string> jsons = new List <string>(stringbuilder.Split('\n'));

                string lastjson = jsons[jsons.Count - 1];

                state.sb.Clear();
                if (!lastjson.EndsWith("}"))
                {
                    lock (state.sb) {
                        state.sb.Append(lastjson);
                    }
                    jsons.RemoveAt(jsons.Count - 1);
                }

                // Put a lock on the updating in world
                lock (world) {
                    world.Update(jsons, ref playerId, team);
                }

                // Set the callback and ask for more data
                state.Callback = UpdateWorld;
                Client.i_want_more_data(state);
            }
        }
        /// <summary>
        /// A method that ends the send infomation
        /// </summary>
        /// <param name="ar"></param>
        private static void SendCallBack(IAsyncResult ar)
        {
            PreservedState pstate = (ar.AsyncState as PreservedState);

            try
            {
                Socket New_Socket = pstate.State_Socket;
                int    SendByte   = New_Socket.EndSend(ar);

                if (SendByte == pstate.buffer.Length)
                {
                    // Safe to shutdown socket
                    pstate.State_Socket.Shutdown(SocketShutdown.Both);
                    pstate.State_Socket.Close();
                }
                else
                {
                    // Keep sending remaining portion
                    Send(New_Socket, encode.GetString(pstate.buffer, SendByte - 1, pstate.buffer.Length - SendByte));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                pstate.State_Socket.Shutdown(SocketShutdown.Both);
                pstate.State_Socket.Close();
            }
        }
Exemple #5
0
        /// <summary>
        /// Helper for Send function.
        /// </summary>
        public static void SendCallback(IAsyncResult stateInResult)
        {
            PreservedState state = (PreservedState)stateInResult.AsyncState;

            // number of bytes that actually got send
            int bytes = state.socket.EndSend(stateInResult);

            lock (sendSync)
            {
                // Get the bytes that we attempted to send
                byte[] outgoingBuffer = state.outgoingBuffer;

                // The socket has been closed
                if (bytes == 0)
                {
                    state.socket.Close();
                    //Debug.WriteLine("Socket closed");
                }

                // Prepend the unsent bytes and try sending again.
                else
                {
                    state.outgoingString = encoding.GetString(outgoingBuffer, bytes,
                                                              outgoingBuffer.Length - bytes) + state.outgoingString;
                    SendBytes(state);
                }
            }
        }
Exemple #6
0
        /// <summary>
        /// This method is called by the Server_Awaiting_Client method when a new client connection needs to be made. Note : This method
        /// is also part of the even loop described in the Server_Awating_Client method.
        /// </summary>
        /// <param name="result">The IAsyncResult object that holds the state object that was passed from the previous method.</param>
        public static void Accept_a_New_Client(IAsyncResult result)
        {
            // Write to the window to show the player that a new client has been accepted.
            Console.WriteLine("Accepting a new Client....");

            // Convert the state object back into a PreservedState object.
            PreservedState state = (PreservedState)result.AsyncState;

            // Pull out the socket listener.
            Socket listener = state.socket;

            // Create a new socket for the client.
            Socket clienthandler = listener.EndAccept(result);


            // We must pass a new state object into the Begin Accept...
            listener.BeginAccept(Accept_a_New_Client, new PreservedState(listener, state.callBack));
            // This fails:
            //listener.BeginAccept(Accept_a_New_Client, state);

            // Update the state object to hold the new client socket instead of the listener.
            state.socket = clienthandler;

            // Call the callback function stored in the state obj.
            state.callBack(state);
        }
Exemple #7
0
        /// <summary>
        /// Attempts to connect to the server via the provided hostname. Calls the given callback function upon connection.
        /// </summary>
        /// <param name="callback">Function to be called (inside the View) when a connection is made.</param>
        /// <param name="hostname">The name of the server to connect to.</param>
        public static PreservedState Connect_to_Server(Action callback, string hostname)
        {
            Socket         socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            PreservedState state  = new PreservedState(callback, socket);

            socket.BeginConnect(hostname, DEFAULT_PORT, Connected_to_Server, state);
            return(state);
        }
Exemple #8
0
        /// <summary>
        /// This method is a callback function to the Send method. It ensures all the data that needs to be sent is sent in the correct order. And it ends when there is no more data
        /// to me sent to the server.
        /// </summary>
        /// <param name="result"></param>
        public static void SendCallBack(IAsyncResult result)
        {
            // The number of bytes that were sent.
            int bytes;

            // Pull the Preserved state obj out of the arObject.
            PreservedState state = (PreservedState)result.AsyncState;

            // Store the socket
            Socket socket = state.socket;

            if (socket.Connected)
            {
                // Retrieve the number of bytes sent
                try
                {
                    bytes = socket.EndSend(result);
                }
                catch (Exception e)
                {
                    socket.Close();
                    return;
                }
            }
            else
            {
                return;
            }

            // Lock this method so multiple threads can be sending data at the same time.
            lock (locker)
            {
                // store the PreservedState buffer into a outgoing buffer.
                byte[] outgoingBuffer = state.buffer;

                // Convert all the buffer data into a string.
                String data = encoding.GetString(outgoingBuffer, bytes, outgoingBuffer.Length - bytes);

                // Iif the string is empty end this send callback
                if (data == "")
                {
                    // If the optional callback was provided in Send(), run it. Else, just return
                    if (state.callBack != null)
                    {
                        state.callBack(null);
                    }
                    else
                    {
                        return;
                    }
                }

                // If there is more data to send call Send again.
                Send(socket, data);
            }
        }
Exemple #9
0
        /// <summary>
        /// This method is a callback from the Connect_To_Server method, it calls the callback stored in the PreservedState obj and then returns control back to Connect_To_Server
        /// </summary>
        /// <param name="arObject"></param>
        public static void Connected_to_Server(IAsyncResult arObject)
        {
            // Pull the Preserved state obj out of the arObject.
            PreservedState state = (PreservedState)arObject.AsyncState;

            // Store the socket
            Socket socket = state.socket;

            // Call the callback function and pass in the state obj.
            state.callBack(state);
        }
Exemple #10
0
        /// <summary>
        /// this handles every client connections
        /// </summary>
        /// <param name="state"></param>
        public void Handle_New_Client_Connections(PreservedState state)
        {
            //set up a message to let us know that a client has connected to the server
            Console.WriteLine("A new client has connected to the server.");

            //set up a callback to recieve the player name
            state.State_Callback = Recieve_Player_Name;

            //Request more data
            NetworkingCode.i_want_more_data(state);
        }
Exemple #11
0
        /// <summary>
        /// Called by OS when socket connects to server.
        /// After this, user should send any initial data, then call i_want_more_data
        /// </summary>
        private static void Connected_to_Server(IAsyncResult stateInResult)
        {
            PreservedState state = (PreservedState)stateInResult.AsyncState;

            state.callback();
            if (!state.socket.Connected)
            {
                return;
            }
            state.socket.EndConnect(stateInResult);
        }
        /// <summary>
        /// Starts the socket connection from the TCP listener and stores the socket in the state, as well as the callback.
        /// </summary>
        /// <param name="ar"></param>
        public static void Accept_a_New_Client(IAsyncResult ar)
        {
            PreservedState listener_state = (ar.AsyncState as PreservedState);

            PreservedState pstate = new PreservedState();

            pstate.State_Socket   = listener_state.State_Socket.EndAccept(ar); // A new socket is "generated" here - every socket needs a new state
            pstate.State_Callback = listener_state.State_Callback;

            pstate.State_Callback(pstate); // Pass in the new state, let the server store it
            listener_state.State_Socket.BeginAccept(Accept_a_New_Client, listener_state);
        }
Exemple #13
0
 /// <summary>
 /// Sends the given data over the network through the given socket.
 /// This function (along with it's helpers 'SendBytes' and 'SendCallback') will allow a program to send data over a socket.
 /// </summary>
 public static void Send(PreservedState state, string data)
 {
     lock (sendSync)
     {
         state.outgoingString += data;
         if (!sendIsOngoing)
         {
             sendIsOngoing = true;
             SendBytes(state);
         }
     }
 }
 /// <summary>
 ///A method that request for more data
 /// </summary>
 /// <param name="state"></param>
 public static void i_want_more_data(PreservedState state)
 {
     try
     {
         state.State_Socket.BeginReceive(state.buffer, 0, PreservedState.buffersize, 0, ReceiveCallback, state);
     }
     catch (Exception e)
     {
         //state.State_Socket.Shutdown(SocketShutdown.Both);
         state.State_Socket.Close();
         //state.State_Callback(state);
     }
 }
Exemple #15
0
        /// <summary>
        /// sends out the player name after the first contact
        /// </summary>
        /// <param name="state"></param>
        public void Recieve_Player_Name(PreservedState state)
        {
            if (NetworkingCode.IsConnected(state.State_Socket))
            {
                //recieve player name from view
                string stringData = state.data.ToString();
                int    EndName    = stringData.IndexOf('\n');
                string name       = stringData.Substring(0, EndName);
                state.data.Remove(0, EndName + 1);

                //create player cube and send to client
                Cube PlayerCube = world.CreatePlayer(name);

                //change callback
                state.State_Callback = Handle_Data_from_Client;

                lock (world)
                {
                    //Add to world and player dictionary
                    world.cubeList.Add(PlayerCube.uid, PlayerCube);
                    PlayerDictionary.Add(PlayerCube.uid, PlayerCube);

                    //adds the socket and the socket's player to a dictionary to keep track of the player for each socket
                    AllSockets.Add(state.State_Socket, PlayerCube);

                    //Seriliaze player cube
                    string message = JsonConvert.SerializeObject(PlayerCube);
                    NetworkingCode.Send(state.State_Socket, message + "\n");

                    //update World
                    UpdateWorld();
                }
                //starts the timer for the server to begin Updating
                //timer.Start();

                //ask for more data
                NetworkingCode.i_want_more_data(state);
            }
            else
            {
                lock (world)
                {
                    AllSockets.Remove(state.State_Socket);
                    if (AllSockets.Count == 0)
                    {
                        //Awaiting Network client connections
                        Start();
                    }
                }
            }
        }
Exemple #16
0
        /// <summary>
        /// Creates a new socket and begins connect
        /// </summary>
        /// <param name="callbackfunction"> Our callback function</param>
        /// <param name="hostname"> The hostname of the server</param>
        /// <returns></returns>
        public static PreservedState Connect_to_Server(Action <PreservedState> callbackfunction, string hostname)
        {
            PreservedState currentState = new PreservedState();

            currentState.stateSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Set the callback
            currentState.Callback = callbackfunction;

            // Begin the connect
            currentState.stateSocket.BeginConnect(hostname, 11000, Connected_to_Server, currentState);

            return(currentState);
        }
Exemple #17
0
        /// <summary>
        ///Process requests from the Web Browser
        /// </summary>
        /// <param name="state"></param>
        public void Stat_Request(PreservedState state)
        {
            int RequestEnd = state.data.ToString().IndexOf('\n');

            string page = "";

            string message = state.data.ToString().Substring(0, RequestEnd - 1);

            state.data.Remove(0, RequestEnd + 2);


            if (message == "GET /players HTTP/1.1")
            {
                string commandText = "SELECT * from Players";
                page = SQLDatabase.ReadFromDatabase(commandText);
            }

            else if (message.Substring(0, 18) == "GET /games?player=")
            {
                string[] GetNameArray = message.Substring(18).Split(' ');

                string name = GetNameArray[0];

                string commandText = "SELECT * FROM Players WHERE Name = '" + name + "'";

                page = SQLDatabase.ReadFromDatabase(commandText);
            }

            else if (message.Substring(0, 14) == "GET /eaten?id=")
            {
                string[] GetNameArray = message.Substring(14).Split(' ');

                string StringGameID = GetNameArray[0];

                int GameID;

                bool BoolGameID = int.TryParse(StringGameID, out GameID);

                string commandText = "SELECT * FROM EatenNames WHERE ID = " + StringGameID;

                page = SQLDatabase.ReadFromEatenNames(commandText, GameID);
            }

            else
            {
                page = "<!DOCTYPE html><html><title> Error </title><body><h5>Error:</h5><p> Cannot connect to server,"
                       + " check URL</p></body></html> ";
            }
            NetworkingCode.Send(state.State_Socket, page);
        }
        /// <summary>
        /// Creates a TCPListener that will wait for any connections to the server
        /// </summary>
        /// <param name="callback"></param>
        public static void Server_Awaiting_Client_Loop(Callback callback, int port)
        {
            //int port = 11000;
            TcpListener listener = new TcpListener(IPAddress.Any, port);
            EndPoint    ep       = listener.LocalEndpoint;

            PreservedState listener_state = new PreservedState(); // State for listener

            listener_state.State_Socket   = listener.Server;      //puts the server in the socket so that Accept_a_new_Client can access it
            listener_state.State_Callback = callback;

            listener.Start();
            listener.BeginAcceptSocket(Accept_a_New_Client, listener_state);
        }
Exemple #19
0
        /// <summary>
        /// Called by OS when new data arrives.
        /// </summary>
        public static void ReceiveCallback(IAsyncResult stateInResult)
        {
            PreservedState state = (PreservedState)stateInResult.AsyncState;
            int            read  = state.socket.EndReceive(stateInResult);

            if (read == 0)
            {
                state.socket.Close();
            }
            else
            {
                state._HandleData(encoding, read);
                state.callback();
            }
        }
Exemple #20
0
        /// <summary>
        /// Callback that sets our player that we get from the server
        /// </summary>
        /// <param name="state"></param>
        public void Received_Player_Callback(PreservedState state)
        {
            string stringData = state.data.ToString();
            int    EndPlayer  = stringData.IndexOf('\n');
            string message    = stringData.Substring(0, EndPlayer);

            state.data.Remove(0, EndPlayer + 1);

            player = JsonConvert.DeserializeObject <Cube>(message);
            world.cubeList.Add(player.uid, player);
            this.Paint += AgCubioGUI_Paint;

            state.State_Callback = Data_Received_Callback;
            NetworkingCode.i_want_more_data(state);
        }
Exemple #21
0
        /// <summary>
        /// This method is the heart of the server code, it asks the OS to listen for new connections, and when a client
        /// makes a connection request it calls the Accept_a_New_Client function. Note : This methos is an event loop, it
        /// continues to listen for new connections continually.
        /// </summary>
        /// <param name="callbackFcn">The desired function you wish to callback to when the Accept_a_New_Client method has finished.</param>
        public static void Server_Awaiting_Client(PreservedState.CallBackFunction callbackFcn, int port)
        {
            // Create a PreservedState object.
            PreservedState state = null;

            // Store the callback function in the PreservedState obj.
            PreservedState.CallBackFunction callBack = callbackFcn;

            // Create a new IPHostEntry based on the hostname.
            IPHostEntry ipHostInfo = Dns.GetHostEntry("localhost");

            // Set IPAddress equal to null
            IPAddress ipAddress = null;

            // Loop through all the ipaddresses in the ipHostInfo List and find the correct one.
            foreach (IPAddress address in ipHostInfo.AddressList)
            {
                // If the address is of type InterNetwork, store this address as the ipAddress.
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ipAddress = address;
                    break;
                }
            }

            // Extablish local end point for the socket.
            IPEndPoint localEP = new IPEndPoint(ipAddress, port);

            // Create a socket.
            Socket listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

            listener.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

            // Associate the listener socket to only this local end point.
            listener.Bind(localEP);

            // We will only allow up to 100 client connections to be backlogged.
            listener.Listen(100);

            // Create a new state object storing the listener socket and the callback function.
            state = new PreservedState(listener, callBack);

            // Print to the Server window, to allow users to see that the server is listening for more players.
            Console.WriteLine("Listening for new connections.....");

            // When a listener has detected a new client trying to add, call Accept_a_New_Client to accept the new cliet.
            listener.BeginAccept(Accept_a_New_Client, state);
        }
Exemple #22
0
        /// <summary>
        /// A callback for connecting and sending the player's name
        /// </summary>
        /// <param name="state"> The state object of the network controller</param>
        private void ConnectCallBack(PreservedState state)
        {
            // If the network is in an error state, set serverError to true
            if (state.error)
            {
                serverError = true;
            }

            // Get the first cubes data and request more data
            state.Callback = GetFirstData;
            Client.i_want_more_data(state);
            // Send player name
            Client.Send(state, PlayerBox.Text + "\n");
            // Name has been set
            nameIt = true;
        }
        /// <summary>
        /// A method that ends the connection
        /// </summary>
        /// <param name="state"></param>
        private static void Connected_to_Server(IAsyncResult state)
        {
            PreservedState pstate = (state.AsyncState as PreservedState);

            try
            {
                pstate.State_Socket.EndConnect(state);
                pstate.State_Callback(pstate);
            }
            catch (Exception e)
            {
                //pstate.State_Socket.Shutdown(SocketShutdown.Both);
                pstate.State_Socket.Close();
                //pstate.State_Callback(pstate);
            }
        }
Exemple #24
0
 /// <summary>
 /// Begins the send to the server
 /// </summary>
 /// <param name="state"></param>
 /// <param name="data"></param>
 public static void Send(PreservedState state, String data)
 {
     try
     {
         // Encode the string to send
         byte[] byteData = Encoding.UTF8.GetBytes(data);
         Socket socket   = state.stateSocket;
         // Begin sending data to the server
         socket.BeginSend(byteData, 0, byteData.Length, 0, SendCallBack, socket);
     }
     catch (Exception e)
     {
         state.error = true;
         Console.WriteLine(e.Message);
     }
 }
Exemple #25
0
        /// <summary>
        /// Attempts to send the entire outgoing string.
        /// </summary>
        private static void SendBytes(PreservedState state)
        {
            if (state.outgoingString == "")
            {
                sendIsOngoing = false;

                //Debug.WriteLine("Done sent.");
            }
            else
            {
                //Debug.WriteLine("Sending: " + state.outgoingString);

                byte[] outgoingBuffer = encoding.GetBytes(state.outgoingString);
                state.outgoingString = "";
                state._BeginSend(outgoingBuffer);
            }
        }
Exemple #26
0
        /// <summary>
        /// Begins receive for more data from the server
        /// </summary>
        /// <param name="state_in_an_ar_object"> The state sent from the caller</param>
        public static void i_want_more_data(PreservedState state_in_an_ar_object)
        {
            PreservedState state = (PreservedState)state_in_an_ar_object;

            try
            {
                Socket client = state.stateSocket;
                // Begin the receive
                client.BeginReceive(state.buffer, 0, PreservedState.BufferSize, 0, ReceiveCallback, state);
            }
            catch (Exception e)
            {
                // Tell the GUI there's an error
                state.error = true;
                state.Callback(state);
                Console.WriteLine(e.Message);
            }
        }
Exemple #27
0
        /// <summary>
        /// This is a constant value that acts as the port number for all server and client communications.
        /// </summary>
        //private const int port = 11000;

        /// <summary>
        /// This method begins the connection process between the server and the client. It also creates and returns the socket to be used in other methods in this class. It takes
        /// in a callback function to be stored in the PreservedState obj and the hostname of the desired server you wish to connect to.
        /// </summary>
        /// <param name="callBack">A callback function to be stored and used later to help in exiting and processing the server data./param>
        /// <param name="hostname">A string containing the server you wish to connect to.</param>
        /// <returns>A socket that enables communication from the server to client.</returns>
        public static Socket Connect_to_Server(PreservedState.CallBackFunction callBack, String hostname, int port)
        {
            // Create a PreservedState object.
            PreservedState state = null;

            // Store the callback function in the PreservedState obj.
            PreservedState.CallBackFunction callBackFcn = callBack;

            // Create a new IPHostEntry based on the hostname.
            IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname);

            // Set IPAddress equal to null
            IPAddress ipAddress = null;

            // Loop through all the ipaddresses in the ipHostInfo List and find the correct one.
            foreach (IPAddress address in ipHostInfo.AddressList)
            {
                // If the address is of type InterNetwork, store this address as the ipAddress.
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ipAddress = address;
                    break;
                }
            }

            // Create a IPEndPoint in order to begin connecting to the server.
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

            // Create a socket
            Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);

            socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, false);

            // Create a PreservedState obj and store the callback function and socket so it can be used later.
            state = new PreservedState(socket, callBackFcn);

            // Begin connecting to the server by calling the Connected_To_Server callback.
            socket.BeginConnect(remoteEP, new AsyncCallback(Connected_to_Server), state);

            // Return the socket.
            return(state.socket);
        }
        /// <summary>
        /// The first callback function to be executed upon connecting with the game server.
        /// It's also called if we fail to connect with the server, in which case we close down
        /// this form and give the player a error message.
        ///
        /// If the connection is successful, we send the server our player name and then start
        /// receiving data from the server.
        /// </summary>
        /// <param name="state"></param>
        private void sendPlayerName(PreservedState state)
        {
            if (state.socket.Connected == false)
            {
                MessageBox.Show("Unable to connect to requested server.");
                MethodInvoker closeWindow = new MethodInvoker(() => this.Close());

                this.Invoke(closeWindow);
            }
            else
            {
                Network.Send(state.socket, playerName + '\n');

                // replace this callback with another callback in the preserved state object
                state.callBack = processReceivedData;

                // Ask for more data from the server
                Network.i_want_more_data(state);
            }
        }
Exemple #29
0
        /// <summary>
        /// The callback of Connect_to_Server which ends the connect
        /// </summary>
        /// <param name="state_in_an_ar_object"> The state passed from the caller</param>
        public static void Connected_to_Server(IAsyncResult state_in_an_ar_object)
        {
            PreservedState currentState = (PreservedState)state_in_an_ar_object.AsyncState;

            try
            {
                // End the connect
                currentState.stateSocket.EndConnect(state_in_an_ar_object);

                // Call the callback
                currentState.Callback(currentState);
            }
            catch (Exception e)
            {
                // Tell the GUI there's an error
                currentState.error = true;
                currentState.Callback(currentState);

                Console.WriteLine(e.Message);
            }
        }
Exemple #30
0
        /// <summary>
        /// This method is called when the user wishes to send data to the server. The callBack parameter
        /// is optional. If a callback is provided, it will be called
        /// </summary>
        /// <param name="socket">The socket this connection is using to talk to the server</param>
        /// <param name="data">The information the user wishes to send to the server.</param>
        public static void Send(Socket socket, String data, PreservedState.CallBackFunction callBackFcn = null)
        {
            // Lock this method so multiple threads can be sending data at the same time.
            lock (locker)
            {
                // Create a new PreservedState object to store the socket and buffer.
                PreservedState state = new PreservedState(socket, null);

                // If the optional callback parameter was provided, add it to the state
                // object so it can be called once the send is complete.
                state.callBack = callBackFcn;

                // Translate the string of data into bytes
                state.buffer = encoding.GetBytes(data);

                // Began sending the bytes of data to the server, and call the callback SendCallBack.
                if (socket.Connected)
                {
                    socket.BeginSend(state.buffer, 0, state.buffer.Length, SocketFlags.None, SendCallBack, state);
                }
            }
        }
Exemple #31
0
        /// <summary>
        /// This method is used to handle the first message back from the server, which will be the player's cube JSON.
        /// </summary>
        /// <param name="ps"></param>
        private void HandleFirstMessageFromServer(PreservedState ps)
        {
            // grab the { ... } part except the new line
            var playerStr = ps.receivedData.ToString().Substring(0, ps.receivedData.Length - 1);
            var cube = JsonConvert.DeserializeObject<Cube>(playerStr);
            world.playerCubes[cube.uId] = cube;
            playerId = cube.uId;
            this.Invalidate();

            // remove the cube data from the state
            ps.receivedData.Clear();

            // after the first player message, server is going to send cubes separated by a new line
            ps.callback = ProcessReceivedData;
            //MessageBox.Show("Success in cubing the player!" + JsonConvert.SerializeObject(cube));

            // make the second call to receive data explicitly
            // ProcessReceivedData will be called now after data is received.
            Network.WantMoreData(ps);
        }
Exemple #32
0
        private void OnConnectedToServer(PreservedState pso)
        {
            // check the connection
            if (pso.errorMsg != null)
            {
                this.Invoke((Action)(() =>
                {
                    MessageBox.Show("Cannot connect to the server at: " + serverTextBox.Text + "\nPlease, make sure your server is reachable.\n" + pso.errorMsg);
                }));
                pso.errorMsg = null;    //reset
                return;
            }

            // if all goes well
            // change panels displayed; the connect panel can be visible first, then when the connection works it is hidden and the game panel is shown (which will start painting)
            this.Invoke(
                (Action)(() =>
                {
                    this.ConnectionPanel.Hide();
                   // this.GamePanel.Show();
                    frameWatch.Start();
                }));
            _ps = pso;
            socket = pso.clientSocket;
            // first get the player cube
            // 1. send name
            Network.Send(socket, nameTextBox.Text);

            // 2. receive data
            // 2.a. Indicate the first time call back funciton to handle player
            pso.callback = HandleFirstMessageFromServer;
            // 2.b. First time call to receive data (server will send the player which is handled by above callback)
            Network.WantMoreData(pso);
        }
Exemple #33
0
        /// <summary>
        /// This method is a callback method when data is received.
        /// It parses the received data into a meaningful Json string.
        /// Then, it tries to convert that to a cube object.
        /// It removes that parsed part of the string from ps.receivedData.
        /// </summary>
        /// <param name="ps">The preserved state object</param>
        private void ProcessReceivedData(PreservedState ps)
        {
            if (ps.errorMsg != null)
            {
                this.Invoke((Action)(() => { MessageBox.Show("Unexpected error while receiveing from server" + ps.errorMsg); }));
                ps.errorMsg = null;
            }
            //System.IO.File.AppendAllText("last.txt", ps.receivedData.ToString());
            //MessageBox.Show("receiving!");

            StringBuilder receivedData = ps.receivedData;
            if (receivedData.Length < 1)
                return;
            // need to make the world thread safe
            lock (this.world)
            {
                // split the data by new line
                string[] jsonCubes = receivedData.ToString().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

                // number of successful conversions to Cube object
                int success = 0;
                int i = 0;
                try
                {
                    while (i < jsonCubes.Length)
                    {
                        // try to onverting to cube object
                        string line = jsonCubes[i];

                        // check it is not of the form: ${.*}^
                        if (!(line.StartsWith("{") && line.EndsWith("}")))
                        {
                            // if this broken line is not the last line:
                            if (i != jsonCubes.Length - 1)
                            {
                                success++; // there is no way to recover what was server saying, so, discard it as a success
                                i++;
                                continue;
                            }
                            else
                                break;
                        }

                        Cube cube = JsonConvert.DeserializeObject<Cube>(jsonCubes[i]);
                        success++;

                        if (cube.food)
                        {
                            // food is eaten remove it.
                            if (cube.Mass == 0.0)
                                this.world.foodCubes.Remove(cube.uId);
                            else
                                this.world.foodCubes[cube.uId] = cube;
                        }
                        else if (cube.Mass == 0.0)
                        {
                            // if some player cube dies remove it.
                            this.world.playerCubes.Remove(cube.uId);
                            // indicate the death if the current player cube died!
                            if (cube.uId == this.playerId)
                                this.dead = true;
                        }
                        else
                        {
                            // if it is not food, it must be a player cube!
                            this.world.playerCubes[cube.uId] = cube;
                        }
                        i++;
                    }

                }
                catch
                {
                }

                // debug purpose
                //System.IO.File.WriteAllText("testfile.txt",                     "# of converted cubes = " + success + "\n" + receivedData.ToString());
                ps.receivedData.Clear();

                if (success > 0)
                    this.Invalidate();

                // need to put back the last unparsed json string
                if ( (success < jsonCubes.Length) && (jsonCubes.Length > 1) )
                    receivedData.Append(jsonCubes[jsonCubes.Length - 1]);
            }
            if (this.dead)
            {
                MessageBox.Show("TODO: Player Died! Restart the Game.");
                socket.Close();
                //this.dead = false;
                return;
            }

            // Ready to receive more data!
            Network.WantMoreData(ps);
        }