I have three classes:
Client
Session
Socket
Both Session & Socket depeand on the Client to create both objects.
A Session depeands on a Socket and no sockets are created without a session.
Should the Client have a function that creates a Session pubically and a Socket privately?
Doesn't it violate the law of demeter?
EDIT:
Current code:
class Client
{
private:
// Connection details
public:
shared_ptr<Socket> createSocket(); // returns a new socket if the connection is opened
}
class Session
{
public:
Session(Client &); // Accepts a client and gets a socket for i/o to the server
}
Now something tells me that the session shouldn't be responsible for getting the socket from the client and that the client should create the session.
Am I right?
It depends. All you are telling us about Client is that it creates both Session and Socket, nothing more.
If Client needs to use both, then there is no violation. If it only creates Socket in order to provide it to Session, I would say this is a violation and Session should get Socket itself.
Related
I have been facing a simple sql connection error, and i m tired of fixing it. I installed sql server 2014 and then sql server 2017, add rules to firewall and even turned off the firewall. services restarted multiple times.
Went to configuration manager, enabled everything, added all the jar required, done clean and build, done all searches on this issue in google, still that same issue comes in again and again. System used are
- Windows 10.
- Sql server management studio 2017.
- Netbean 8.1
code :-
import java.sql.*;
public class DbConnect {
public static void main(String[] args) throws SQLException,ClassNotFoundException {
String url = "jdbc:sqlserver://localhost:1433;databaseName=productlist;user=db2017;password=db2017";
//commented :-String url = "jdbc:sqlserver://DESKTOP-7CI6DU0\\NIT2017:1433;databaseName=productlist;user=db2017;password=db2017";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
System.out.println("test");
Statement sta = conn.createStatement();
String Sql = "select * from productlist";
ResultSet rs = sta.executeQuery(Sql);
while (rs.next()) {
System.out.println(rs.getString("CatName"));
} } }
Below is exception error comes again again, after so much troubleshooting.
Exception in thread "main" com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties, check that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:171)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1033)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:233)
at DbConnect.main(DbConnect.java:11)
C:\Users\Nitish\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
Before giving up, thought to check here...
Your commented-out connection string suggests you are connecting to a named instance. A default SQL Server instance (not-named) listens on port 1433 unless configured otherwise. A named instance uses a dynamic port, which is not 1433, unless configured otherwise. One can have only one default instance per machine and every SQL instance must listen on a different port.
You can identify the port a SQL instance is listening on using SQL Server Configuration Manager or by viewing the SQL Server error log. The error log will include messages for each interface and port SQL Server is listening on. The message will be like "Server is listening on [ 'any' 1433]." The port can be changed using SSCM and will be effective after restarting the SQL Service.
To test port connectivity, you can use TELNET:
TELNET YourServer 1433
You'll see and empty window if the connection is successful, otherwise and error.
If you don't have TELNET installed, you can test the port connectivity with this Powershell command from a command-prompt window:
powershell -Command echo ((new-object Net.Sockets.TcpClient).Client.Connect('YourServer', 1433)) 'success'
You'll see the success message upon successful connection, otherwise a socket exception.
Note that the dynamic port is assigned during installation and the instance will attempt to use the same port upon each startup. However, be aware the port number could change if that port is unavailable at startup. One can configure a static port (including port 1433) using SSCM to avoid the port number changes of a named instance.
i am reading this article https://polycrystal.org/posts/2012-05-25-active-record-connection-pool-fairness.html and it states that every http reuest create a new connection pool. is it true??
If it is true then what if a http request creates two threads that needs to access database then will that two threads create two separate connection pool agian or they will use the connection pool created by a http request.
Thanks,
Not request, but every worker process. The whole concept of connection pooling is to eliminate the need for establishing a db connection in every request.
In flash, we can create a server socket with this:
protected var socket:ServerSocket = new ServerSocket();
protected function createServer():void
{
socket.bind(1234,"0.0.0.0");
socket.addEventListener(ServerSocketConnectEvent.CONNECT, clientConnectedHandler);
// start listening for connections
socket.listen();
}
With this, any flash application try to connect to the server socket with the port 1234 will get connected. How can I do verification on connection to make sure it is connected from my application before accepting the connection on server socket?
Thank you.
SockerServer instance will throw errors on failure:
RangeError — This error occurs when localPort is less than 0 or greater than 65535.
ArgumentError — This error occurs when localAddress is not a
syntactically well-formed IP address. IOError — when the socket
cannot be bound, such as when: the underlying network socket (IP and
port) is already in bound by another object or process. the
application is running under a user account that does not have the
privileges necessary to bind to the port. Privilege issues typically
occur when attempting to bind to well known ports (localPort < 1024)
this ServerSocket object is already bound. (Call close() before
binding to a different socket.) when localAddress is not a valid local
address.
You can use try..catch statements to handle those errors.
If those errors aren't thrown, opening port went successfully :)
We are intended to develop a service, which always stay connected to email server, so that whenever a user triggers a mail, it will sent by using the connect instead of getting a new connection and sending the mail.
Is is possible that we always stay connection to email server using JAVA Mail API??.
kindly help me in this.
When you connect to SMTP server (also when using javax.mail API), you use a socket connection (see the src of SMTPTransport and Transport classes). Sockets let you connect to a remote server and that connection remains open until explicitly closed. This means that theoreticaly you could create a connection and them reuse it.
However, many SMTP servers are pretty evil and will kill the connection if you are using it "too slow" or if you try to resuse your SMTP session to often. (I looked up postfix settings for you.)
The Java Mail API allows you to create the connection and close it whenever you want to. Smth. like this:
Transport transport = session.getTransport("smtp");
transport.connect();
transport.sendMessage(msg, addressArray);
// you can do transport.close(); later
However, because of the fact how the SMTP servers are, you can't just execute connect() once and forget it. At most, what you can do, is properly handle forced disconnects by reconnecting again. There is a notification mechanism in the Java Mail API to do that (take a look at the usage of the notifyConnectionListeners method)
However, because of the fact how the SMTP servers are, you can't just
execute connect() once and forget it. At most, what you can do, is
properly handle forced disconnects by reconnecting again.
Agreed!
You can in fact reuse the JavaMail SMTP connection with below logic:
Transport transport = null;
MimeMessage message = null;
Properties prop = new Properties();
// load all smtp properties
Session session = Session.getDefaultInstance(prop, null);
transport = session.getTransport("smtp");
for (EachMail eachMail : list) {
if (!transport.isConnected()) {
if (port != null && port.length() > 0) {
transport.connect(host, Integer.parseInt(port), "<username>", "<password>");
} else {
transport.connect(host, "<username>", "<password>");
}
}
// set all mail attributes from eachMail object
message.saveChanges();
transport.sendMessage(message, message.getAllRecipients());
}
Works like a charm. Cheers!
If you want an always up connection you should create your Transport outside of the sending method, but to avoid excpetions on sending (SMTPSendFailedException 421 Timeout data client) you should check if the transport is connected, and if not to connect it again befor sending:
if (!transport.isConnected())//make sure the connection is alive
transport.connect();
transport.sendMessage(message, message.getAllRecipients());
How do I go about creating a socket based status reporting system for an AIR app?
What I have in mind, is you connect to the app via socket connection with some sort of terminal. It presents you with a list of options, you issue commands back, and it reports back any stats and messages.
(This is for an app running on a remote kiosk, connected via 3G.)
Use a ServerSocket and listen for connections. Add the onConnect listener to tell when a client has connected and use the ProgressEvent to tell when the client has sent data over the socket. Here are two tutorials and an excerpt on how to get started with a ServerSocket:
import flash.net.ServerSocket;
import flash.events.ServerSocketConnectEvent;
private function onConnect(e:ServerSocketConnectEvent):void
{
var incomingSocket:Socket = e.socket;
// You can now read and write data from the socket instance
}
var server:ServerSocket = new ServerSocket();
server.addEventListener(Event.CONNECT, onConnect);
server.bind(8888); // Pass in the port number you want to listen on
server.listen();
Basic.
More complex example which accepts client data transfer.