javascript - Send data from Client to Client within localhost with ajax

I want to make a connect four game with the option to play online against another person connected to my game which is hosted through localhost (within the same WiFi). It's possible to play a game on both computers but not against each other.

Firstly I want to get a simple string send from one client to the other with an ajax call. My attempt:

$(".column").click(function () {
      $.ajax({
          url: "GetBoard",
          method: "GET",
          data: { "currentplayer" : currentPlayer },
          success: function (data) {
              alert("success");
          }
      });
)};

The controller method I used:

[HttpPost]
public ActionResult GetBoard(string currentPlayer)
{
    return View(currentPlayer);
}

I don't really understand how to send data with ajax or how to receive and work with it within a controller.

1 Answer

  1. Jerry- Reply

    2019-11-13

    In order to make application available over wifi network you can do these steps.

    Step#1

    Publish you application on local host so that if other user is on same network then they can browse the local host using listening port. Example: localhost:8733

    Step#2

    You can use SignalR to broadcast changes in game real time so that other users on same local host will be able see the changes.

    Example

    If you want to broadcast move of particular Id then you can create you hub class like this

     public class GameHub : Hub
    {
        public void Send(string move, int Id)
        {
            // Call the addNewMessageToPage method to update clients.
            Clients.All.addNewMessageToPage(move,Id);
        }
    }
    

    Html

     <script>
        $(function () {
            // Reference the auto-generated proxy for the hub.  
            var chat = $.connection.chatHub;
    
         //this will write to page
            chat.client.addNewMessageToPage = function (move, Id) {
    
            console.log("New move "+move);
                    console.log("New Id "+Id);
    
            };
    
    
            // Start the connection.
            $.connection.hub.start().done(function () {
       //this will broadcast move to all pages
                $('#broadcast').click(function () {
                     chat.server.send($('#currentmove').val(), $('#currentId').val());
    
                });
            });
        });
    
    </script>
    

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>