java.net.ConnectException: Connection refused: connect. Data Grip [duplicate] - mysql

I'm trying to implement a TCP connection, everything works fine from the server's side but when I run the client program (from client computer) I get the following error:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at TCPClient.main(TCPClient.java:13)
I tried changing the socket number in case it was in use but to no avail, does anyone know what is causing this error & how to fix it.
The Server Code:
//TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception {
String fromclient;
String toclient;
ServerSocket Server = new ServerSocket(5000);
System.out.println("TCPServer Waiting for client on port 5000");
while (true) {
Socket connected = Server.accept();
System.out.println(" THE CLIENT" + " " + connected.getInetAddress()
+ ":" + connected.getPort() + " IS CONNECTED ");
BufferedReader inFromUser = new BufferedReader(
new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(
new InputStreamReader(connected.getInputStream()));
PrintWriter outToClient = new PrintWriter(
connected.getOutputStream(), true);
while (true) {
System.out.println("SEND(Type Q or q to Quit):");
toclient = inFromUser.readLine();
if (toclient.equals("q") || toclient.equals("Q")) {
outToClient.println(toclient);
connected.close();
break;
} else {
outToClient.println(toclient);
}
fromclient = inFromClient.readLine();
if (fromclient.equals("q") || fromclient.equals("Q")) {
connected.close();
break;
} else {
System.out.println("RECIEVED:" + fromclient);
}
}
}
}
}
The Client Code:
//TCPClient.java
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String FromServer;
String ToServer;
Socket clientSocket = new Socket("localhost", 5000);
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(
System.in));
PrintWriter outToServer = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
while (true) {
FromServer = inFromServer.readLine();
if (FromServer.equals("q") || FromServer.equals("Q")) {
clientSocket.close();
break;
} else {
System.out.println("RECIEVED:" + FromServer);
System.out.println("SEND(Type Q or q to Quit):");
ToServer = inFromUser.readLine();
if (ToServer.equals("Q") || ToServer.equals("q")) {
outToServer.println(ToServer);
clientSocket.close();
break;
} else {
outToServer.println(ToServer);
}
}
}
}
}

This exception means that there is no service listening on the IP/port you are trying to connect to:
You are trying to connect to the wrong IP/Host or port.
You have not started your server.
Your server is not listening for connections.
On Windows servers, the listen backlog queue is full.

I would check:
Host name and port you're trying to connect to
The server side has managed to start listening correctly
There's no firewall blocking the connection
The simplest starting point is probably to try to connect manually from the client machine using telnet or Putty. If that succeeds, then the problem is in your client code. If it doesn't, you need to work out why it hasn't. Wireshark may help you on this front.

You have to connect your client socket to the remote ServerSocket. Instead of
Socket clientSocket = new Socket("localhost", 5000);
do
Socket clientSocket = new Socket(serverName, 5000);
The client must connect to serverName which should match the name or IP of the box on which your ServerSocket was instantiated (the name must be reachable from the client machine). BTW: It's not the name that is important, it's all about IP addresses...

I had the same problem, but running the Server before running the Client fixed it.

One point that I would like to add to the answers above is my experience-
"I hosted on my server on localhost and was trying to connect to it through an android emulator by specifying proper URL like http://localhost/my_api/login.php . And I was getting connection refused error"
Point to note - When I just went to browser on the PC and use the same URL (http://localhost/my_api/login.php) I was getting correct response
so the Problem in my case was the term localhost which I replaced with the IP for my server (as your server is hosted on your machine) which made it reachable from my emulator on the same PC.
To get IP for your local machine, you can use ipconfig command on cmd
you will get IPv4 something like 192.68.xx.yy
Voila ..that's your machine's IP where you have your server hosted.
use it then instead of localhost
http://192.168.72.66/my_api/login.php
Note - you won't be able to reach this private IP from any node outside this computer. (In case you need ,you can use Ngnix for that)

I had the same problem with Mqtt broker called vernemq.but solved it by adding the following.
$ sudo vmq-admin listener show
to show the list o allowed ips and ports for vernemq
$ sudo vmq-admin listener start port=1885 -a 0.0.0.0 --mountpoint /appname --nr_of_acceptors=10 --max_connections=20000
to add any ip and your new port. now u should be able to connect without any problem.
Hope it solves your problem.

Hope my experience may be useful to someone. I faced the problem with the same exception stack trace and I couldn't understand what the issue was. The Database server which I was trying to connect was running and the port was open and was accepting connections.
The issue was with internet connection. The internet connection that I was using was not allowed to connect to the corresponding server. When I changed the connection details, the issue got resolved.

In my case, I gave the socket the name of the server (in my case "raspberrypi"), and instead an IPv4 address made it, or to specify, IPv6 was broken (the name resolved to an IPv6)

In my case, I had to put a check mark near Expose daemon on tcp://localhost:2375 without TLS in docker setting (on the right side of the task bar, right click on docker, select setting)

i got this error because I closed ServerSocket inside a for loop that try to accept number of clients inside it (I did not finished accepting all clints)
so be careful where to close your Socket

I had same problem and the problem was that I was not closing socket object.After using socket.close(); problem solved.
This code works for me.
ClientDemo.java
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException,
IOException {
Socket socket = new Socket("127.0.0.1", 55286);
OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream());
os.write("Santosh Karna");
os.flush();
socket.close();
}
}
and
ServerDemo.java
public class ServerDemo {
public static void main(String[] args) throws IOException {
System.out.println("server is started");
ServerSocket serverSocket= new ServerSocket(55286);
System.out.println("server is waiting");
Socket socket=serverSocket.accept();
System.out.println("Client connected");
BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str=reader.readLine();
System.out.println("Client data: "+str);
socket.close();
serverSocket.close();
}
}

I changed my DNS network and it fixed the problem

You probably didn't initialize the server or client is trying to connect to wrong ip/port.

Change local host to your ip address
localhost
//to you local ip
192.168.xxxx

I saw the same error message ""java.net.ConnectException: Connection refused" in SQuirreLSQL when it was trying to connect to a postgresql database through an ssh tunnel.
Example of opening tunel:
Example of error in Squirrel with Postgresql:
It was trying to connect to the wrong port. After entering the correct port, the process execution was successful.
See more options to fix this error at: https://stackoverflow.com/a/6876306/5857023

In my case, with server written in c# and client written in Java, I resolved it by specifying hostname as 'localhost' in the server, and '[::1]' in the client. I don't know why that is, but specifying 'localhost' in the client did not work.
Supposedly these are synonyms in many ways, but apparently, not not a 100% match. Hope it helps someone avoid a headache.

For those who are experiencing the same problem and use Spring framework, I would suggest to check an http connection provider configuration. I mean RestTemplate, WebClient, etc.
In my case there was a problem with configured RestTemplate (it's just an example):
public RestTemplate localRestTemplate() {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", <some port>));
SimpleClientHttpRequestFactory clientHttpReq = new SimpleClientHttpRequestFactory();
clientHttpReq.setProxy(proxy);
return new RestTemplate(clientHttpReq);
}
I just simplified configuration to:
public RestTemplate restTemplate() {
return new RestTemplate(new SimpleClientHttpRequestFactory());
}
And it started to work properly.

There is a service called MySQL80 that should be running to connect to the database
for windows you can access it by searching for services than look for MySQL80 service and make sure it is running

It could be that there is a previous instance of the client still running and listening on port 5000.

Related

Connect to MySQL Database using sockets

I am following up from my last question, where I was suggested to use sockets for a real time chat application using MySQL database. I have been researching some information about the usage of sockets in flutter, after trying several times and several different codes and failing, I clicked inside another stackoverflow question about sockets and found out this code snippet:
import 'dart:io';
import 'dart:async';
Socket socket;
void main() {
Socket.connect("localhost", 4567).then((Socket sock) {
socket = sock;
socket.listen(dataHandler,
onError: errorHandler,
onDone: doneHandler,
cancelOnError: false);
}).catchError((AsyncError e) {
print("Unable to connect: $e");
});
//Connect standard in to the socket
stdin.listen((data) => socket.write(new String.fromCharCodes(data).trim() + '\n'));
}
void dataHandler(data){
print(new String.fromCharCodes(data).trim());
}
void errorHandler(error, StackTrace trace){
print(error);
}
void doneHandler(){
socket.destroy();
}
I may be wrong but I think this may be the way to connect to my database, if it is not please help me out, I would appreciate it. But I can't find a way to write in the database name, username and password in order to access the data from a specific MySQL database.

How to find CPU MEMORY usage with docker stats command?

I am using docker-java API to execute docker API in my project. I didn't find any suitable method which lists down docker CPU memory usage as
GET /v1.24/containers/redis1/stats HTTP/1.1 with the help of docker-java API
Dependency
compile group: 'com.github.docker-java', name: 'docker-java', version: '3.1.2'
Code
public static void execute() {
DockerClient dockerClient = DockerClientBuilder.getInstance().build();
dockerClient.statsCmd("containerName");
}
I didn't get any output
Tell me how to execute docker stats with docker-java api
This works for me
public Statistics getNextStatistics() throws ProfilingException {
AsyncResultCallback<Statistics> callback = new AsyncResultCallback<>();
client.statsCmd(containerId).exec(callback);
Statistics stats;
try {
stats = callback.awaitResult();
callback.close();
} catch (RuntimeException | IOException e) {
// you may want to throw an exception here
}
return stats; // this may be null or invalid if the container has terminated
}
DockerClient is where we can establish a connection between a Docker engine/daemon and our application.
By default, the Docker daemon can only be accessible at the unix:///var/run/docker.sock file. We can locally communicate with the Docker engine listening on the Unix socket unless otherwise configured.
we can open a connection in two steps:
DefaultDockerClientConfig.Builder config
= DefaultDockerClientConfig.createDefaultConfigBuilder();
DockerClient dockerClient = DockerClientBuilder
.getInstance(config)
.build();
Since engines could rely on other characteristics, the client is also configurable with different conditions.
For example, the builder accepts a server URL, that is, we can update the connection value if the engine is available on port 2375:
DockerClient dockerClient
= DockerClientBuilder.getInstance("tcp://docker.baeldung.com:2375").build();
Note that we need to prepend the connection string with unix:// or tcp:// depending on the connection type.

IOT: Only one usage of each socket address (protocol/network address/port) is normally permitted

I'm trying to run my first IoT on my Raspberry Pi 3.
But using this code ....
public void StartServer()
{
Task.Run(async () =>
{
listener = new StreamSocketListener();
listener.Control.KeepAlive = true;
listener.Control.NoDelay = true;
await listener.BindServiceNameAsync(port.ToString());
});
}
I get this error at BindServiceNameAsync...
Exception thrown: 'System.Runtime.InteropServices.COMException' in mscorlib.ni.dll
WinRT information: Only one usage of each socket address (protocol/network address/port)
is normally permitted.
In appmanifest I have checked "Internet (Client & Server)".
Any idea why I get this error?
Thanks
Most likely the port that you are trying to use is already being used by another process. Try a different port.

Derby automatically start server within java application and connect to database

Trying to connect to a database on the system automatically.
The database is in the default Derby folder, created via NetBeans.
What I want to do is start the server and connect to the already existing database.
public void startServer() throws Exception {
NetworkServerControl server = new NetworkServerControl();
server.start(prntWrt);
}
#Override
public void start(Stage primaryStage) throws IOException, Exception {
startServer();
Pane root = (Pane) FXMLLoader.load(InteractiveFictionGame2.class.getResource("MainMenu.fxml"));
Scene scene = new Scene(root);
primaryStage.setTitle("MainMenu");
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.show();
}
It seems that the server does start but for some reason I can't connect to the database as it thinks it is non existant.
String host = "jdbc:derby://localhost:1527/InteractiveGameDatabase";
String unm = "Kylar";
String pswrd = "aswzxc";
public void loadImg() throws IOException {
try {
String SQL = "select vista from location where ycoordinate = ? and xcoordinate = ?";
Stage stage = new Stage();
con = DriverManager.getConnection(host, unm, pswrd);
stmnt = con.prepareStatement(SQL);
stmnt.setInt(1, ycoord);
stmnt.setInt(2, xcoord);
rs = stmnt.executeQuery();
rs.next();
fis = rs.getBinaryStream(1);
BufferedImage imgt = null;
try {
imgt = javax.imageio.ImageIO.read(fis);
} catch (IOException ex) {
System.out.println("Image failed to load.");
}
Image newImg = SwingFXUtils.toFXImage(imgt, null);
fadeInImage();
img_1.setFitHeight(880);
img_1.setImage(newImg);
img_1.setPreserveRatio(true);
img_1.setCache(true);
CountDownLatch doneLatch = new CountDownLatch(1);
animateUsingTimeline();
stck1.getChildren().addAll();
Scene scene = new Scene(stck1);
stage.setTitle("Interactive Fiction Game");
stage.setScene(scene);
stage.setFullScreen(true);
stage.show();
rs.close();
stmnt.close();
con.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
I get an error "The connection was refused because the database InteractiveGameDatabase was not found.". If I start the server through the NetBeans IDE and then run the application everything is perfect. Any help will be appreciated.
Since you specified:
String host = "jdbc:derby://localhost:1527/InteractiveGameDatabase";
as your connection URL, the Derby Network Server is looking for the database using the relative database name "InteractiveGameDatabase". Since that is a relative name, not an absolute name, the Derby Network Server will look for the database in its home directory, which is typically whatever was the current directory when you started the Derby Network Server.
So probably what's going here is that when you run the Derby Network Server in NetBeans, it runs with a certain directory as its home directory, according to how NetBeans starts it up.
But when you run the Derby Network Server yourself, by hand, it runs in a different directory as its home directory, because you didn't precisely start it up in the same directory where NetBeans starts it up, and hence it can't find the database InteractiveGameDatabase in this new directory.
You could:
Always use the NetBeans-started Derby Network Server
Start your own Network Server, but arrange to do so in the same directory where NetBeans starts the Derby Network Server
Start your own Network Server, but change your connection URL to specify the full absolute path to the location where the NetBeans-started Derby Network Server was run, so that your Network Server can access that directory when you go to open the database.
There are many other possibilities, but hopefully these are enough to give you an idea about what's going on.

DatagramSocket bind() and connect() difference?

I read the documentation, but it is not clear whats the difference between bind() and connect() methods.
bind() causes the socket to listen for incoming requests on a particular interface/port. In other words, it's used by servers to respond to incoming requests. Only one socket can bind a port.
connect() causes the socket to make a connection to an address/port serviced by a different socket. In other words, it's used by clients to connect to a server. Multiple clients can connect to a port. NOTE: connect() is not required for use with UDP (datagram) sockets, only TCP/IP. UDP is a broadcast protocol, and connect() does not even require that a socket is listening to the other end.
Something like this (adapted from the docs and untested) should send and receive the message "Hello, turnip!" to itself on port 12345:
package
{
import flash.events.DatagramSocketEvent;
import flash.net.DatagramSocket;
public class TestClass
{
private var serverSocket:DatagramSocket = new DatagramSocket();
private var clientSocket:DatagramSocket = new DatagramSocket();
public function TestClass():void
{
this.serverSocket.bind(12345, "127.0.0.1");
this.serverSocket.addEventListener(DatagramSocketDataEvent.DATA, dataReceived);
this.serverSocket.receive();
send("Hello, turnip!");
}
public function sendData(message:String):void
{
var data:ByteArray = new ByteArray();
data.writeUTFBytes(message);
try
{
clientSocket.send(data, 0, 0, "127.0.0.1", 12345);
trace("sending: " + message);
}
catch (error:Error)
{
trace(error.message);
}
}
private function dataReceived(e:DatagramSocketDataEvent):void
{
var data:String = e.data.readUTFBytes(e.data.bytesAvailable);
trace("received: " + data);
}
}
}
Bind is used to allocate a particular port by system to a socket and no other process can use this particular port until the first process releases it.It's typically used in server side.
Listening and binding are not same, listen puts the socket into listening state, in other words, the server socket is saying that I am listening to incoming client connections now.
Connect is used by client to connect to listening server socket.
Finally accept is used by server socket when a client wants to connect to it while it was in the listening state.
Simple explanation on this is:
Say you have created server and client sockets as serverSock and clientSock
When you say serverSock.bind((localhost,portnumber)), it means serverSock is bound to address 'localhost' at unique port 'portnumber'
Whereas if you say clientSock.connect((localhost, portnumber)) at client side , it means we are telling client to connect with server with hostname as 'localhost' (which can be server ip address) and at port 'portnumber' using clientSock socket.