Avoid MySQL Connection during Websocket - mysql

I have a question regarding the flow of go lang code.
In my main function, I am opening mysql connection and then using `defer" to close the connection at the end of the connection.
I have route where WebSocket is set up and used.
My Question is will program open connection every time, WebSocket is used to send and receive a message or will it just open once the page was loaded.
Here is how my code looks like:-
package main
import (
// Loading various package
)
func main() {
// Opening DB connection -> *sql.DB
db := openMySql()
// Closing DB connection
defer db.Close()
// Route for "websocket" end point
app.Get("/ws", wsHandler(db))
// Another route using "WebSocket" endpoint.
app.Get("/message", message(db))
}
Now, while a user is at "message" route, whenever he is sending the message to other users, Will mysql - open and close connection event will happen every time, when the message is being sent and receive using "/ws" route?
Or will it happen Just once? whenever "/message" route and "/ws" event is called the first time.
My Purpose of using "db" in "wsHandler" function is to verify and check if the user has permission to send a message to the particular room or not.
But there is no point opening and closing connection every second while WebSocket emits message or typing event.
What would be the best way to handle permission checking in "/ws" route, if above code is horror? Considering a fact there will be few hundred thousand concurrent users.

Assuming db is *sql.DB your code seems fine, I'm also assuming that your example is incomplete and your main does not actually return right away.
The docs on Open state:
The returned DB is safe for concurrent use by multiple goroutines and
maintains its own pool of idle connections. Thus, the Open function
should be called just once. It is rarely necessary to close a DB.
So wsHandler and message should be ok to use it as they please as long as they don't close DB themselves.

Related

how to close database connection without terminating the server connection in golang

Is there any way to close the database connection without terminating the HTTP server?
my code:
func thisone(w http.ResponseWriter,r *http.Request){
/*connect the db*/
defer database.Close()
/*query the database*/
}
func main(){
http.HandleFunc("/route",thisone)
http.ListenAndServe(":8000",nil)
}
what this does is after querying the database it terminates the program and stopped listening to the port
but I want to keep listening to the port even after the database connection is close.
so is there any way to do that
Thank You
Every time you are querying the database you are calling thisone() and every time that function is executed is closing the database connection. Try to put database.Close() inside main function.
func main(){
defer database.Close()
http.HandleFunc("/route",thisone)
http.ListenAndServe(":8000",nil)}
That's a little weird that you have an error putting up database.Close() in the main function because I recently made an API Rest with Go a little similar. You can see the code here.I hope it is useful.
Github API Rest with Go

how to delete post using socket.io mysql nodejs express

I'm learning to do simple messaging app which allows user to add the status and in real time update it to feeds of everyone.
I am using socket.io, mysql, nodejs and express.
User can send message in real time.
In browser startup, it load all data in database.
I'd like to ask how could I delete message based in ID ?
Thanks.
Without knowing how you currently pull the post cant give as detailed of a response, but lets assume you emit that from your socket as well..
The websockets are a persistent connection to the users, because of that both client and server can emit or receive commands. With that knowledge we can now just 'emit' from the 'client' to the 'server' a command that the post has been 'deleted' when the 'client' emits to the 'server' the socket server can then delete the post from the DB, after the deletion has been completed it will then 'emit' to the 'client' who has a listener for 'postDelete' (or whatever you want to call it) that may contain the updated post list OR it could have another call that runs an update post function etc.
** Edit **
To add a bit more to this.
It's important to remember that socket.io is really just a message broker of sorts. It can GET and EMIT messages, you tell it how and what to do for each.
So to the question as to how you would go about 'deleting' the message is really no different then how you would go about it normally
(client) user clicks delete, 'emits' to server
Server is 'listening' for the 'emit' on X command to delete
Server gets command, inside of '.on' for delete is your 'delete' code (will probably be SQL to remove from DB)
After command is run and successful you will then 'emit' from server with the new payload of 'posts'
Client has a ".on" to listen for new or updated 'posts' server 'emits' to this
Client get new 'emits' from server with the updated JSON and updates the screen.

URLLoader does not resond to .close()

My application requires that I am able to abort/close a URLLoader instance at any point in the post-connect stage; that is, regardless if I have connected and the file transfer has already begun, or whether I have connected, and the file transfer has yet to commence (the server has not begun sending the file yet).
Here is my code:
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.load(new URLRequest("myText.txt"));
This is what I have noticed:
When I connect to a server, and the server starts sending the file immediately, DURING the actual file transfer, if I invoke myTextLoader.close(), it aborts immediately. This is expected. I can monitor this by executing the SWF in Firefox,and noticing that when I issue the close(), the network connecion goes from Pending to aborted.
However, if I connect to the server, and the file transfer has not actually begun yet (I have confirmed the connect event has fired, and the server has simply not begun sending the file), then myTextLoader.close() has no effect. Only AFTER the first bytes start being transferred from the server, will .close() have any effect. I can verify the connection is stuck in Pending in Firebug.. .close() has no effect until the transfer has started.
Any ideas how to work around this issue? I need to be able to invoke .close() and have the connection torn down regardless of the connection stage.
First thing I would think of, is create a bool "aborted" that is set to true where the close() method is invoked.
Like :
function abort():void {
_aborted = true;
myTextLoader.close();
}
Then check for its value anywhere in the onProgress event or any similar event, to actually call the URLLoader close() method again whenever its value is true...
function onProgress(evt:ProgressEvent):void {
if (_aborted) {
myTextLoader.close();
}
}
Its not a pretty thing and is an ugly workaround, but this could work, since when the first bits are actually received, you'll know if you already wanted to close it or not.
Did you find any bug report on that anywhere ?... I doubt it could be an intended behavior...
3rd party AS3 HTTPClient (https://github.com/gabriel/as3httpclient) appears to not exhibit this issue with close().

How to handle socket error during logout routine

I am writing an instant messaging library. Currently, when a SocketException is raised while reading or writing to the socket, I start the logout routine from inside the application, passing the SocketException to the enduser as an argument of the LogoutEventArgs. This gives the end user a way of seeing what underlying exception actually caused the unrequested logout.
My question, is what am I to do, if during a user call to the Logout function, the socket actually throws an Exception.
Example - End user calls Logout function, and while the logout function is waiting for existing requests to end gracefully, the socket throws an exception in the reading thread.
I have two options as I see it -
Pretend the error didn't occur, and just act like the socket disconnected as part of our Logout.
When the socket exception is raised, see if a logout request is taking place, and if so, override it. Resulting in the original Logout request throwing an AlreadyLoggedOutException, as well as a separate logout event which passes the exception in the LogoutEventArgs.
Also, slightly related - What am I to do if the server initiates a shutdown that wasn't requested (ie.. the read call returns null).. the .NET Messenger server has a tendency to do this if you send a request it doesn't like. Do I treat this as an exception in itself?
I have found the whole disconnecting/logging out part of my library to be a major thorn in my side. I just can't seem to wrap my head around it. Does anyone know of any open source code applications that handle this situation beautifully?
I have been trying to tackle this thing in my head for so long, it's driving me mad.
I decided not to pass the SocketException to the end user, as a disconnect is not truly an exception and should be expected and dealt with. Instead there is a LogoutReason property on the LogoutEventArgs which specifies why the logout occured.
I decided that if the disconnect occurs during Logout then that's not actually an exception for, as the logout was going to disconnect anyway. I simply disregard the exception in this case.

Best way to connect to database for this application

I have a Delphi application which hits a database (usually MySql) every 60 seconds through a TTimer. The application is more or less an unattended bulletin board. If the network drops the application needs to continue running and connect back to the database when the connection is back. Often it might be over broadband, so chances are the connection is not always the best.
I am using the TAdoConnection component. This is opened at application startup and remains open. Whenever I need to make a new query I set the Connection to the open TAdoConnection. But I am finding this is not very reliable if there is a network drop.
What is the best way to connect to the database in this instance?
I have seen ways where you can build the connection string directly into the TAdoQuery. Would this be the proper way? Or is this excessively resource intensive? Sometimes I need to open 5-10 queries to get all the information.
Or how about doing this in the TTimer.OnTimer event:
Create TAdoConnection
Do All Queries
Free TAdoConnection
Thanks.
You should use single TAdoConnection object to avoid setting connection string to each component. Keep your connection object closed and open it when you need to access data. Something like this:
procedure OnTimer;
begin
MyAdoConnection.Open;
try
// Data access code here
...
finally
MyAdoConnection.Close;
end;
end;
You can additionally put another try/except block around MyAdoConnection.Open to catch situation where network is not available.
About second part of your question, best would be to put all your data access components in data module that you will create when you need to run data access procedures. Then you can put all your data access code in that data module and separate it from rest of the code.
You could try to open connection in OnCreate event of datamodule, but be careful to handle possible exceptions when opening connection. Close connection in OnDestroy event. Then you can use that datamodule like this:
procedure OnTimer;
var myDataModule : TMyDataModule;
begin
myDataModule := TMyDataModule.Create;
try
// Data access code here
myDataModule.DoSomeDatabaseWork;
finally
myDataModule.Free;
end;
end;