I have to built a Client/Server application where the server side is just an application that passes data from one client to the other.
The client will be written in C# and I want to write the server in NodeJS, if that's possible. I'll try to explain the idea behind this.
It's best to explain this if you see this application as a 1vs1 game. So multiple clients can connect to an Async server. One client will be matched with another client as in a Player1 / Player2 context.
Player1 can make a "move". A POCO will be converted to a JSON format for example. That will then be send to the server and the server should know to what opponent (Player2) it should sent the data. Then in return Player2 can make a move and then new data will be send back through the server back to Player1.
So the server needs to have a list of all the connected players/clients. So it can keep track of what player play vs who and what scores they have etc. Basically, a stateless environment.
I've been thinking about writting the server in C# with the SocketAsyncEventArgs class. But since NodeJS/Socket.IO is already an optimized lib, that would save time if I could do it in that.
I just need to know if it's possible to do this in NodeJS. Or should I stick to a C# server?
Okey,
I argue that it is possible if you use something like SocketIO4Net.Client at your C# side to open connection to your node.js server.
From the docs:
SocketIO4Net.Client can interact with Socket.IO instances in a very
similar manner as Socket.IO JavaScript clients. This project aims to
fill the JavaScript client and C# client gap for Socket.IO, and retain
a very similar application experience.
And for the purpose of storing player lists etc. at server, it is easy. You define javascript object just as players where you add your connected clients and use for example socket.id as identifier.
// Players currently at server
var players = {};
you do this usually by listening socket connection event, for example:
... somewhere in your code ...
var io = require('socket.io').listen(httpServer);
... somewhere in your code ...
// run on new client connection..
io.sockets.on("connection", function (socket) {
// adding to list of players you have in your server
// Player can be your own declared class as you like it to be
players[socket.id] = new Player({
nickname: "playerNameExample"
});
});
However, if your game is more like match-making 1vs1 it would be worth to consider that you add always your separate playing partners to different rooms in server. So exchanging messages travels only between relevant participants. See socket.io rooms
As for the resources where to go next: best choice is to just google "multiplayer game with socket.io" which will give wide variety of results. Just as this: Building-multiplayer-games-with-nodejs if you are completely new to node.js googling hello world with node.js might be better to do first.
Due note: If you don't know the basics and haven't tried programming anything with node.js you are not ready to make working multiplayer game, advance step by step.! ( and yes I am looking this now from game perspective as you instructed but behavior of games can be applied to many apps as well ). Cheers.
Related
In my Unity3D game the Player plays himself through short levels, which at the beginning take about 4 seconds. The goal is to get the best possible clear time in each level. I am currently saving these clear times locally, but I would like to upload them to an SQL Server, to be able to create a leaderboard for each level.
Since performing the SqlConnection.Open() command takes about 1-2 seconds, sometimes also 3, I was wondering whether I should keep a static connection always open, ready to execute any queries that I want to run.
Are there any unwanted and dangerous side-effects when doing it?
Edit: This is the code that I use for opening the SqlConnection.
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder()
{
DataSource = dataServer,
UserID = userId,
Password = password
};
SqlConnection connection = new SqlConnection(builder.ToString());
connection.Open();
First I'll answer this question:
Are there any unwanted and dangerous side-effects when doing it?
Assuming you keep this code in your Game (client) and the SQL Server is not client-side but in a server of yours located somewhere, a simple Client Reverse Engineer will be able to grab your credentials from your connection string and use them to gain Unauthorized access to your database. (NEVER trust the client)
With that being said, I would suggest you use a simple server-side technology (php,Socket App, Java servlet, etc..) along with the SQL that the client will send the information there and then to the database.
Example:
1) Client-> Posts Data -> PHP
2) PHP -> Connects -> SQL Database
3) PHP -> Inserts data -> SQL Database
Like this you can also retrieve the results of your ladder from the database by asking php (or whatever technology you are using) to send your data to the client.
Best wishes in your progress, and feel free to contact me for any additional information!
I want to display progress on my screen/page/view just as happens in console. So when i click install button, my "textarea" control should start displaying progress like
connecting to database
connection successful
running script a.sql
running script b.sql
operation complete
connection closed
Is textarea the correct control for this purpose?
it Seems like there will be too many trips from server to the client just to write the progress on screen how can i minimize it?
To be able to do this easily, you can use SignalR which simplify all the hassle of which underlying technology to be used based on the version of the browser it will choose the best communication protocol (WebSocket, LongPolling..etc).
Behind SignalR, one of the underlying used technologies is websockets, it doesn't send anything except keep an open full duplex channels between server and client, in case any update in the server it will push this update to the client. most popular sites use websockets for keeping open channels between server and client.
SignalR uses actually websockets however it will downgrade to use long polling for example in case of old browsers that don't support websocket's connection upgrades.
You have the option to use the websockets directly in case you are assured your clients use new browsers.
One last thing Stackoverflow as a big and heavy loaded site uses websockets to update once there is a new answer or comment for example.
The general approach for this is just sending an ajax request every second or so and asking for an update from the server.
<div>
<pre id="status">
</pre>
</div>
setInterval(function () {
$.ajax("/getUpdate?someParam=1234").then(function (result) {
// result is whatever JSON object you send from the server
$("#status").innerText = result.someProp;
});
}, 1000);
It might look something like the above. Note that it's doing a request every second and storing the message from the server in the pre element.
I have this web application (MVC using C#) that serves like an advertisement in my client's office. My client will open this "advertisement page" and display it on a big screen to their customers.
What happen is, every 30 minutes or so, the page will automatically refresh to fetch latest data from the database, however, they are using WIFI to connect to our server and sometimes the connection is very slow (or lost connection completely). My client requested me to write a code to prevent the page from refreshing if the connectivity is bad or no internet connection. (They do not want to show "No Internet Connection" on their advertisement TV)
I know I cannot do anything from the server side code because it is the client's machine that want to detect the internet connection, so leaving client side code as the only option. I am not good at this, can anyone help me out?
I'd suggest a "ping" sent via ajax:
var timeStart= new Date().getTime();
$.ajax({
url:"url-to-ping-response-file",
success:function(){
var timeNow = new Date().getTime();
var ping = timeNow - timeStart;
//less than one second
if(ping < 1000){
window.location.reload();
}
}
});
You can use the Circuit Breaker Pattern to gracefully handle intermittently connected environments.
Here are 2 open source JavaScript implementations. I have never used either of them, so I cannot attest to their quality.
https://github.com/yammer/circuit-breaker-js
https://github.com/mweagle/circuit-breaker
You can also make use of
if (navigator.onLine) {
location.reload();
}
This will not detect slow internet. Now, I don't understand your web layout but for sites that I work on I tend to get HTML content and DATA as separate calls. I do this with a MVVM/MVC pattern which is worth learning. I use angularjs it is very awesome.
Now.. you can also use good old jQuery to replace the content have a read of this Replace HTML page with contents retrieved via AJAX you could couple this with the .onLine check.
http://www.w3schools.com/jsref/prop_nav_online.asp
I'm currently using the NEST ElasticSearch C# Library for interacting with ElasticSearch. My project is an MVC 4 WebAPI project that basically builds a RESTful webservice for accessing directory assistance information.
We've only just started working with NEST, and have been stumbling over the lack of documentation. What's there is useful, but it's got some very large holes. Currently, everything we need works, however, we're running into an issue with connections sometimes taking up to a full second. What we'd like to do is use some sort of connection pooling, similar to how you'd interact with SQL Server.
Here is the documentation on how to connect using nest: http://mpdreamz.github.com/NEST/concepts/connecting.html
Here is the relevant code snippet from our project:
public class EOCategoryProvider : IProvider
{
public DNList ExecuteQuery(Query query)
{
//Configure the elastic client and it's settings
ConnectionSettings elasticSettings = new ConnectionSettings(Config.server, Config.port).SetDefaultIndex(Config.index);
ElasticClient client = new ElasticClient(elasticSettings);
//Connect to Elastic
ConnectionStatus connectionStatus;
if (client.TryConnect(out connectionStatus))
{
// Elastic Search Code here ...
} // end if
} // end ExecuteQuery
} // end EOCategoryProvider
From looking at the documentation, I can't see any provisions for a connection pool. I've been thinking about implementing my own (having, say 3 or 4 ElasticClient objects stored, and selecting them round-robin style), but I was wondering if anyone had a better solution. If not, does anyone have advice on the best way to implement a connection pool by hand? Any articles to point to?
Thanks for anything you guys come up with.
Update: This seems to have been related to calling TryConnect on every request, and the particular network setup. The problem completely disappeared when using a machine on the same network as the Elastic box; My development machine (which averages 350ms to the Elastic box) seemed to fail to make http connections sometimes, which caused the long times in TryConnect.
You don't have to call TryConnect() each time you do a call to Elasticsearch. It's basically a sanity check call for when your application starts.
NEST is the C# REST client for Elasticsearch and the default IConnection uses WebRequest.Create which already pools TCP connections.
Review the actual implementation: https://github.com/elastic/elasticsearch-net/blob/master/src/Elasticsearch.Net/Connection/HttpConnection.cs
Reusing ElasticClient won't offer any performance gains since each call already gets its own HttpWebRequest. The whole client is built stateless on purpose.
I am however very interested in why calls are taking 1 second for you. Could you post the actual NEST code, how you are are measuring the calls and describe your data.
Disclaimer: I'm the author of NEST.
I was reading that question (How to create a simple proxy in C#?) that is near of my wishes.
I simply want develop a c# app that, by example, monitors Firefox, IE, etc and logs all navigated pages. Depending of the visited page, I want to block the site (like a parental filter).
Code snippets/samples are good, but if you can just tell me some direction of that classes to use I will be grateful. :-)
I’ll answer appropriate for a parent: ala "Parental Controls"
You can start out with a proxy server when the kids are less than about 10 years old. After that, they will figure out how to get around the proxy (or run their own client applications that bypass the proxy). In the early teen years, you can use raw sockets.
Type this program into Visual Studio (C#).
class Program
{
static void Main(string[] args)
{
try
{
byte[] input = BitConverter.GetBytes(1);
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.91"), 0));
s.IOControl(IOControlCode.ReceiveAll, input, null);
int bytes = 0;
do
{
bytes = s.Receive(buffer);
if (bytes > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes));
}
} while (bytes > 0);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
Note that this is just a “snippet”, lacking appropriate design and error checking. [Please do not use 'as-is' - you did request just a head start] Change the IP address to your machine. Run the program AS Administrator (use “runas” on the command line, or right-click “Run as Administrator”). Only administrators can create and use raw sockets on modern versions of windows. Sit back and watch the show.
All network traffic is delivered to your code (displayed on the screen, which will not look nice, with this program).
Your next step is to create some protocol filters. Learn about the various internet application protocols (assuming you don't already know), modify the program to examine the packets. Look for HTTP protocol, and save the appropriate data (like GET requests).
I personally have setup filters for AIM (AOL Instant Messenger), HTTP, MSN messenger (Windows Live Messenger), POP, and SMTP. Today, HTTP gets just about everything since the kids prefer the facebook wall to AIM nowadays.
As the kids reach their early-to-mid teenage years, you will want to back-off on the monitoring. Some say this is to enable the kids to “grow up”, but the real reason is that “you don’t wanna know”. I backed off to just collecting URLs of get requests, and username/passwords (for emergency situations) that are in clear text (pop, basic auth, etc.).
I don't know what happens in late teen years; I cannot image things getting much worse, but I am told that "I have not seen anything yet".
Like someone earlier said, this only works when run on the target machine (I run a copy on all of the machines in the house). Otherwise, for simple monitoring check your router - mine has some nice logging features.
My final comment is that this application should be written in C/C++ against the Win32 API directly, and installed as a service running with administrative rights on the machine. I don't think this type of code is appropriate for managed c#. You can attach a UI in C# for monitoring and control. You have to engineer the code so as to have zero noticeable effect on the system.
Your approach will depend on whether or not you are installing this application on the same box you are using to browse or on a separate proxy server.
If you are doing this on a separate server it will be easier to accomplish this in C# / managed code, as you will be simply writing a C# proxy server that client pc's will have point to. System.Net.Sockets namespace TcpListener and TcpClient will be your friend.
If, however, you are installing this on the same machine then take a look WinPcap and and SharpPCap and perhaps Fiddler for some ideas.
Hope that helps.