Multiplayer Server to Person Game - websocket

I am indeed new here, but I have been reading the responses for.. since I've began programming.
I am still new, and absolutely fresh out the womb when it comes to networking. But I'll keep this brief so you can give a conclusive answer.
I have a webserver and a domain name. I would like to use websockets to make an environment in which both players can move at the same time on the same screen. For example, if the mouse controlled a dot, and two people connected to a global "world" then a single person could see the dot of the other person in real time. An example of something like this would be rumpetroll.com.
I don't expect to get a whole lot about how to design a game like RuneScape (although I think that the idea is almost the same). I just want some in-depth explanation of how to get this cool little interaction going.
Any links to how to program to sockets would be GREATLY appreciated, because all I can find on the internet is the concept. Nothing on the mechanics and what each command may do.
Anyway, thanks guys.

You will need a server and a client. I am assuming you know JavaScript, so I will provide an example that uses it on both sides.
The server
You will need nodejs, install it following the instructions on the site.
I will provide examples using socket.io, since you asked for websockets, but keep in mind that there are also other solutions, like Faye, which is worth looking at.
Put yourself in a new folder, run npm install socket.io, this will download the required code for the server; then paste this code in a file named server.js
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function (socket) {
socket.emit('new-connection', { message: 'we have a new user!' });
socket.on('message-from-client', function (data) {
console.log(JSON,stringify(data));
});
});
Start the server by typing node server.js, you should see info - socket.io started in the console.
The client
Paste this code in a file called index.html and open it with your favorite web browser
<script src="http://localhost:8000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8000');
socket.on('new-connection', function (data) {
alert(JSON.stringify(data));
socket.emit('message-from-client', { message: 'hi' });
});
</script>
As soon as you navigate to http://localhost:8000 you will see two things:
an alert greeting you
a message in the console where you started the server
this will happen each time you navigate to that url, try navigating to it with two different browsers or in a incognito / private browsing window. Each time you should see the alert and the message.
This is the basic setup. From here you could complicate things as much as you like to, if you will be using this solution consider passing data around in JSON, as I showed in the examples.
Where to go from here
As you can see it is really easy, if you want to show a dot, that will appear for all users, bind the client mouse movements to a function that will send the position to the server and have it broadcast to all the other connected users (should be something like socket.broadcast.emit but look into the docs as I'm not sure), or you could simply send an event, something like updated-mouse-position which will have a function bound to it that will handle the graphical part.
Hope this helps, feel free to add comments if you have doubs / problems with the basic configuration.

Related

VueJS SPA dynamic baseURL for axios

I've searched and searched and can't seem to find a pattern for this. I'd consider myself an intermediate Vue dev, however, the backend is my strong suit. I'm working on an app that will be white-labeled by resellers. While it's possible to have multiple builds, avoiding that would be ideal. The setup is a stand-alone vue-cli SPA connecting to a Laravel api backend and using the Sanctum auth package. So I need calls to the same domain. The issue: resellers will be on their own domain. The ask: Is there a pattern/solution for dynamically loading configs (mainly baseURL) for different domains (other items would by theme/stylesheet). Currently I have a few typical entries:
i.e. axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL
Basically, based on the domain the site is being served on, I'd like a dynamic/runtime config. I feel like this has been solved, but I can't seem to use the right search terms for some direction, so anything is helpful. I've tried a few things:
1) Parsing in js, but can't seem to get it to run early enough in the process to take effect? It seems to work, but I can't get it to "click"
2) Hit a public API endpoint with the current domain and get the config. Again, can implement, but can't seem to get it to inject into the Vue side correctly?
Any resources, pattern references or general guidance would be much appreciative to avoid maintaining multiple builds merely for a few variables. That said, I don't think there's much overhead in any of this, but also open to telling my I'm wrong and need multiple builds.
End Result
url visited is https://mydomaincom
then baseURL = https://api.mydomiancom
url visited https://resellerdomaincom
then baseURL=https://api.resellerdomaincom
I don't think there is a common pattern to solve your problem - I haven't found anything on the net.
The best software design solution could be the following:
have a single back-end
distribute only the client to your customers/resellers
Obviously the back end could see the domain of the application from which the request comes and manage the logic accordingly.
Good luck with your project.
Honestly how the question is put it's not really clear to me. Although my usual pattern is to:
Create an axios instance like so:
export const axiosInstance = axios.create({
// ...configs
baseURL: process.env.VUE_APP_URL_YOU_WOULD_LIKE_TO_HIT
})
and then whenever I make a request to some api, I would use this instance.
EDIT: According to your edit, you can either release the client to each customer, and have a .env file for each and every of them, or you can have a gateway system, where the client axios end point is always the same, hitting always the same server, and then from there the server decides what to ping, based on your own logic

how to work with a network socket (if correct term) in general and in Chrome

I have encountered something new in Chrome which I've not seen before and am unfamiliar with. It appears to be some type of persistent socket (best term I know of).
Up to now I've been familiar with each AJAX call being the way to contact a server, each with a request/response if the connection is successful. And each one would show in the Name column in the console. Plus, I could "Replay XHR" as an option. And the tabs Headers/Preview/Response/Timing were helpful. However this appears to be grouped and the data I see in the chat window I can't find in any of the JSON objects on the list. What is the correct name for this, and is there any way to see the individual headers/response from each call?
This is a screenshot:

How to obtain firefox user agent string?

I'm building an add-on for FireFox that simulates a website, but running from a local library. (If you want to know more, look here)
I'm looking for a way to get a hold of the user-agent string that FireFox would send if it were doing plain http. I'm doing the nsIProtocolHandler myself and serve my own implementation of nsIHttpChannel, so if I have a peek at the source, it looks like I'll have to do all the work myself.
Unless there's a contract/object-id on nsHttpHandler I could use to create an instance just for a brief moment to get the UserAgent? (Though I notice I'll need to call Init() because it does InitUserAgentComponents() and hope it'll get to there... And I guess the http protocol handler does the channels and handlers so there won't be a contract to nsHttpHandler directly.)
If I have a little peek over the wall I notice this globally available call ObtainUserAgentString which does just this in that parallel dimension...
Apparently Firefox changed how this was done in version 4. Have you tried:
alert(window.navigator.userAgent);
You can get it via XPCOM like this:
var httpHandler = Cc["#mozilla.org/network/protocol;1?name=http"].
getService(Ci.nsIHttpProtocolHandler);
var userAgent = httpHandler.userAgent;
If for some reason you actaully do need to use NPAPI like you suggest in your tags, you can use NPN_UserAgent to get it; however, I would be shocked if you actually needed to do that just for an extension. Most likely Anthony's answer is more what you're looking for.

strutrs2 and ajax(Displaying dynamic value on jsp)

Im pretty new to struts2 and Ajax ,Actually i have a drop down menu in JSP lets say first.jsp, When user select a choice from dropdown menu,I am calling a function of Action class lets say Method1.In this method i am fetching some value from DB(lets say:a,b,c) and one value from java memory lets say d.Then I am forwarding to second.jsp and display all the parameters(a,b,c and d) in tabular format.
Now problem is that the parameter d is dynamic ,this is updating by some other application and if its change then I have to show it on JSP wihout any action.
One solution is I use in second.jsp , so after interval of 10 second again Mehod1 will call and it will fetch value(a,b,c) from db and updated value of d from java memory. and disply it to second.jsp.But in this case i am unnecessary retrieving value from db while my purpose is just to get value d from memory.This is working but this is causing my application to slower.
Can any body suggetst some other solution? or can i do it using ajax and how?
Any other advice? any help is appreciated.try to be more clear, i'm in lack of ideas in this problem, even it sounds like a classic :I have spend hours trying to play around with this but have got nowhere
Okay... What you're asking is a little fuzzy so let me rephrase:
You have a user (USER1) who opens a web page and sees some data.
You have a second user (USER2) (who may be an application) who is able set a value from time to time.
When USER2 updates that value you want USER1 to see it change in their open browser window?
If this is the case you need to understand basic ajax. For that get these demo applications working:
This example uses dojo and perhaps the S2 ajax tag lib I don't remember I prefer not to use ajax tags (as they are deprecated and prefer jquery for ajax):
http://struts.apache.org/2.x/docs/struts-2-spring-2-jpa-ajax.html
This example here shows a very similar application but using jquery, no tag library, upgraded to Spring 3, it still needs polish:
http://www.kenmcwilliams.com/Downloads/
Now that you know how to get data via ajax, look at the request with firebug. You'll see that the request is just like a typical function call, the browser keeps waiting for the data to come back.
What you do is simply not return from the action until new data is provided. This is called long polling see: http://en.wikipedia.org/wiki/Comet_%28programming%29#Ajax_with_long_polling
If you have not written a simple chat program, using just terminal windows I recommend you do so. Two windows per client (client-send, client-receive windows) and you'll need a server program. I remember hacking one together in a few hours using _Thinking In Java 2nd Edition (Later books took out the networking section if I remember correctly). Anyways between understanding client server interaction and long polling will let you get things working. It would be fun to extend the simple terminal based chat application to a S2 ajax chat application. Would make an awesome tutorial! PS: This is just an application of the producer/consumer problem (If you understand that then I guess you don't need to do the fun exercise).
The interfaces would look very pretty if the server was managed by spring. I know there must be nice servers already written but I am not familiar with any, but would love to hear of one.

out of this world Comet programming and a web-based chat

Current Project Setup
I've been working on a web-based chat, similar to Facebook chat. At the current state, I listen for incoming chats and check for new messages in an existing chat is by doing...
setTimeout(function() { listenForIncomingChat() }, 500);
setTimeout(function() { checkForIncomingMessages( ...params... ) }, 500);
... so doing the setTimeout() makes sure these functions are always running. Depending on how many chat windows I have open, Firebug's console can go crazy with POSTs to the server :)
Obviously this is really inefficient, but it is the only way I could get things to work. Now I'm looking for the ways to make it better, to do it correctly!
Some Research
Now, I have heard about Comet Programming and that this is the way to open a long-lived HTTP connection with the server, but I'm not familiar with the technology or the ideas behind Comet. WebSockets for HTML5 is probably even better, but since that is not in full swing nor is it supported by all browsers, I'll stick with what works.
According to Wikipedia, there are several ways to develop with the Comet style: Streaming (hidden iFrame, XMLHttpRequest) or AJAX with long polling (XMLHttpRequest, Script tag). However, I don't know anything about this. I've also read about the AJAX Push Engine (APE) and it looks cool, but I don't want to use a third-party for the time being.
I've recently stumbled upon WebChat 2.0 so I'm going to be looking through the source code to try and understand how it all works.
On to the question(s)
So where can I find example code/tutorials on how to get started with this kind of project? How would I implement the Comet technique? How do I set up the long-lived HTTP connection with the server?
Here's an example of a chatroom using node.js, source code here.
I believe the client uses polling, but this example is interesting because the server side is in JS too, and node.js is efficient for this type of stuff.

Resources