Suddenly can't connect to external server in Java - java

It's been working perfectly fine all day long, now suddenly I can't connect. I can connect through the browser (and so can you: http://secure.exoterragame.com/noxastra/login.php), but it won't work in my Java application. I get an UnknownHostException.
URL register = new URL("http://secure.exoterragame.com/noxastra/login.php" +
"?username=" + request.Username +
"&password=" + request.Password);
URLConnection conn = register.openConnection();
I am completely stumped. Does anyone know why this would happen?
(Yes, we'll be using https in the final version :P)

Do a packet sniff to see what's going on behind the scenes. (I recommend Wireshark for all platforms.)
I had a similar problem in Flash once and was tearing my hair until I realized it was a bug in the VM and it was giving me timeouts without ever sending any packets!
I don't think Java will have such a bug, but the point is, sniffing is sometimes invaluable.
Maybe there's a DNS/hosts-file update which your browser has gotten, but the program not (or the other way around?) Maybe the program's getting stuck on a (local) firewall? Maybe it does login successfully but breaks on a redirect response? (I don't even know if URL is capable of doing that, but still...) Maybe you've enabled/disabled IPv6 somewhere?

jcomeau#intrepid:/tmp$ cat test.java; javac test.java; java test
import java.net.*;
public class test {
public static void main(String args[]) throws Exception {
URL register = new URL(
"http://secure.exoterragame.com/noxastra/login.php" +
"?username=" + "guest" +
"&password=" + "guest");
URLConnection conn = register.openConnection();
}
}
Doesn't throw an exception for me. Perhaps https://stackoverflow.com/users/800237/adithya-surampudi 's suggestion will work.

Related

Connection Refused, how to solve?

I've been working on a service with java tutorial, and was listening to it through localhost:8082. It was working just fine, but since I've turned off the computer it returns the error connection refused when I try to listen to it, and the only ports that present different responses are 8080 and 8081, which get the same error when I try to listen to the service through them.
Here's the code:
package io.vertx.book.message;
import io.vertx.core.json.JsonObject;
import io.vertx.rxjava.core.AbstractVerticle;
import io.vertx.rxjava.core.eventbus.Message;
import rx.Single;
public class HelloConsumerMicroservice extends AbstractVerticle {
#Override
public void start() {
vertx.createHttpServer()
.requestHandler(
req -> {
Single<JsonObject> obs1 = vertx.eventBus()
.<JsonObject>rxSend("hello", "Luke")
.map(Message::body);
Single<JsonObject> obs2 = vertx.eventBus()
.<JsonObject>rxSend("hello", "Leia")
.map(Message::body);
Single
.zip(obs1, obs2, (luke, leia) ->
new JsonObject()
.put("Luke", luke.getString("message")
+ " from " + luke.getString("served-by"))
.put("Leia", leia.getString("message")
+ " from " + leia.getString("served-by"))
)
.subscribe(
x -> req.response().end(x.encodePrettily()),
t -> req.response().setStatusCode(500).end(t.getMessage())
);
})
.listen(8082);
}
}
That's the response I've got:
I don't know why it stopped working, but I've already browsed through a lot of answers and already tried cleaning my cache, but no improvements. Could anyone help?
I'm using Linux 18.04, Chrome/Firefox (both get connection refused).
As your using Ubuntu it might be your firewall not allowing connections to that port.
Open a terminal and type
sudo ufw allow 8082
Hopefully that helps
Somehow after shytting everything down and restarting the machine, everything came back to normal, so... Don't know what happened, but it's all right now... It might've been used by something else. Thanks anyways for the help!

PGJDBC: could not receive data from client:

Dear StackOverFlowers,
I was trying event-driven LISTENER/NOTIFY on Postgres 9.6 (Windows 10).
I followed PGJDBC example given by Steve Taylor at https://www.openmakesoftware.com/postgresql-listen-notify-events-example/.
I started by downloading pgjdbc-ng-0.7-complete.jar and have put that in my CLASSPATH replacing standard JDBC driver.
When I am trying to connect to Postgres database using pgjdbc driver, I am getting an error:
connection received: host=127.0.0.1 port=50325
connection authorized: user=postgres database=scott
could not receive data from client: An existing connection was forcibly closed by the remote host.
Here are my system variables:
DBHost: localhost
DBName: scott
DBPort: 5432
DBUserName: postgres
DBPassword: postgres
I am not getting past the first hurdle, rest looks like Mount Everest. Please help me. Should you be needing the code, I am following Steve's code ditto.
Further to Joseph Larson's answer, the database is always running. I have connected to Postgres database from PGADMIN and Java successfully. I think issue is with the connect string. From Java when I am using standard JDBC which is provided by Postgres I am using URL like jdbc:postgresql://localhost:5432/dbname but PGJDBC suggests a different connect string like JDBC:PGSQL://localhost:5432/dbname. I tried to connect with that string (forcibly), it did not work. There is no method in PGJDBC PGDataSource for providing URL directly. I had to go through:
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
And what URL it is sending to Database I am not able to figure out. Please suggest me a connect string and this problem is solved.
thanks
Thanks very much for asking me to post error messages:
Exception in thread "main" java.lang.NullPointerException
at com.impossibl.postgres.system.BasicContext.loadLocale(BasicContext.java:294)
at com.impossibl.postgres.system.BasicContext.init(BasicContext.java:273)
at com.impossibl.postgres.jdbc.PGConnectionImpl.init(PGConnectionImpl.java:251)
at com.impossibl.postgres.jdbc.ConnectionUtil.createConnection(ConnectionUtil.java:182)
at com.impossibl.postgres.jdbc.AbstractDataSource.createConnection(AbstractDataSource.java:723)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:66)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:58)
at PGListenNotify.<init>(PGListenNotify.java:26)
at PGListenNotify.main(PGListenNotify.java:37)
Here is source code:
import java.sql.SQLException;
import java.sql.Statement;
import com.impossibl.postgres.api.jdbc.PGConnection;
import com.impossibl.postgres.jdbc.PGDataSource;
public class PGListenNotify
{
PGConnection connection;
public PGListenNotify()
{
String DBHost = System.getenv("DBHost");
String DBName = System.getenv("DBName");
String DBUserName = System.getenv("DBUserName");
String DBPassword = System.getenv("DBPassword");
try
{
PGDataSource dataSource = new PGDataSource();
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
connection = (PGConnection) dataSource.getConnection();
Statement statement = connection.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
PGListenNotify ln = new PGListenNotify();
}
}
This looks like the Windows locale bug in pgjbdc-ng. It has been addressed, try the latest version 0.8.1.
The latest releases have detailed documentation related to asynchronous notifications here.
If it still fails to execute on your Windows system, please create an issue here.
Did you actually start a database server? I didn't know PostgreSQL server could run on Windows, but I've never tried.
I would simplify your problem a little. I know nothing about psql on Windows, but on Mac, I would start the server and then use the psql command (it's part of PostgreSQL) to ensure the server was up and running.
If you're to connecting, then the problems can be:
-There is no server at all
-The server isn't running on the port you're attempting
-The server isn't listening for connections on host 127.0.0.1 but could be listening on the actual IP address of your machine
-I'm not sure about that particular error, but username, password, or database may not exist.
I'd use psql to figure out which of those possible reasons is the real problem. That isolates out your program as being part of the problem, and it becomes entirely one of managing your database server.

jTDS 1.2.7 and SQL Server 2000 Default instance

a very simple snippet:
private static final String mydriver="net.sourceforge.jtds.jdbc.Driver";
private static final String myurl="jdbc:jtds:sqlserver://xx.xxx.xxx.xxx/myDatabase";
private Connection myconn;
[stuff]
public int connect(final String username,final String password){
try{
Class.forName(mydriver);
myconn=DriverManager.getConnection(myurl,username,password);
} catch (ClassNotFoundException e) {
return 1;
} catch (SQLException e) {
return 2;
}
return 0;
}
Note please, a number of points:
1. As a control, I have installed a very simple client called MSSQL Client by Pascal Nunes. It takes IP,DB,user,pwd and connects SUCCESSFULLY (without specifying port 1433). I have verified with Pascal himself, he is using jTDS 1.2.7, so I made sure my jTDS version was in line with his.
2. I have tried a number of parameters and parameter combinations, but nothing seems to work
3. I know neither the server nor the network can be responsible, since Pascal's app works
4. Pascal's app has "Full Network Access" according to my Nexus 7. I have given my app:
android.permission.INTERNET in the manifest. I don't see any other permissions that might apply, but I'm new at this
5. Otherwise, there must be jTDS parameters that need to be morphed away from their default. If so, damned if I can find 'em.
Any ideas?
I am not sure if you still face this problem. Happened to find this question while searching for something else. But I believe I am the Pascal you mention and MSSQL client is the application you are referring to. I will try to answer your question as best I can:
jtds doesn't require you to specify a port. 1433 is taken by default.
Building a connection string is very well documented for jtds. This is how I build the connection string:
String properties = ";domain=" + domain + ";user=" + id + ";password=" + pass;
String conn = "jdbc:jtds:sqlserver://" + Server + "/" + Database + properties;
The app only needs network(android.permission.INTERNET) access.
Hope the answer helps you and others who come along.

WebSockets, GlassFish, Grizzly -- can't connect

I am trying to get started with WebSockets, and trying to write a simple application to send messages back and forth via a websoket.
However, it looks like the socket that I am trying to create never gets connected. Why can that be?
Below is the code of my WebSockets class. When .onConnect() is called, it logs:
I am socket, I was connected. Am i connected? - false
Update: in JavaScript, where I create the socket in question, the readyState is 1, which means "socket open, communication is possble".
import a.b.Misc; //writes logs.
import com.sun.grizzly.websockets.BaseServerWebSocket;
import com.sun.grizzly.websockets.DataFrame;
import com.sun.grizzly.websockets.WebSocketListener;
public class ChatWebSocket_v2 extends BaseServerWebSocket {
private String user;
public ChatWebSocket_v2(WebSocketListener... listeners) {
super(listeners);
}
public String getUser() {
if (user == null) {
Misc.print("User is null in ChatWebSocket");
throw new NullPointerException("+=The user is null in chat web socket");
}
return user;
}
public void setUser(String user) {
Misc.print("Just set user: " + user);
this.user = user;
}
#Override
public void onMessage(String message) {
Misc.print(message +"\n");
}
#Override
public void onMessage(byte[] message) {
Misc.print(new String(message) +" << Bytes\n");
}
#Override
public void onConnect() {
Misc.print("I am socket, i was connected. Am i connected? - " + this.isConnected());
}
#Override
public void onClose(DataFrame df) {
Misc.print("I am socket, i was closed");
}
}
If you're just trying to make a connection somewhere, you might want to try this instead. There is a live working demo and you can download the javascript code and play with it yourself. Note that the javascript code only works if you have it installed on a server (due to browser security because it's 'fancy'.) There is also a step by step browser-based client tutorial in the works that I will post as soon as it's ready. Most proxy servers haven't been upgraded to handle websockets so they will screw up connection request and most people won't be able to connect to websocket servers from work. Firefox 7 (release) or Google Chrome 14 or later support the latest version of the websocket protocol that the demo server runs.
If you want to try to get the grizzly demo working, you might have some debugging to do and maybe I'll help with that. Note that in comments below the article, other people said they couldn't get it working either and I haven't found any follow up. At this point it seems no better than the echo app above even if we do get it running and is possibly overly complicated and underly documented if you're just trying to get started. But if you want to try to get it running, you should 'git' the latest version of the code here, which was at least committed recently and may be fixed.
Then make sure that app.url in the application javascript file is set to your installation directory. His is hard-coded as:
url: 'ws://localhost:8080/grizzly-websockets-chat/chat',
If you're using Firefox 7, the javascript needs to be modified to use the Moz prefix, for example:
if (typeof MozWebSocket != "undefined") { // window.MozWebSocket or "MozWebSocket" in window
ok
} else if (window.WebSocket) { // he uses if ("WebSocket" in window)
ok
} else {
do your print "browser doesn't support websockets"
}
.... then if the browser supports websockets
websocket = new WebSocket(app.url); or
websocket = new MozWebSocket(app.url);
// depending on which it is.
The HLL websocket server demo code has this all sorted out.
(another) UPDATE: As I work through grizzly myself, I found on the Quick Start in the glassfish admin console, there's a hello sample that's pretty easy to set up and run. You'll find instructions there. The sample directory also contains a war file named: websocket-mozilla; so I guess its supposed to use websockets. Someone who's familiar with jsp should review the source code. All I can see is that it's using an http session. No mention of a websocket at all. It's a lot like the hello sample.

How can I make a java applet connect with a server?

Please excuse my noobishness as I am teaching myself Java and don't know a lot.
I'm trying to make a multiplayer game that runs from Java applets, I have a server-side program working that will accept strings of text, but all my attempts to find code for applets have failed.
My best attempt looks like it works but I think fails to connect to the server, any ideas why? (localIP is my correct IP and works fine in other tests)
public void init()
{
try
{
socket = new Socket(localIP, 5555);
inStream = new DataInputStream(socket.getInputStream());
outStream = new PrintStream(socket.getOutputStream());
}
catch(Exception e)
{
never reached
}
}
I don't mind scrapping this if someone can tell me a better way to do it or any way at all.
a java applet can only connect to the server from which it was downloaded. if you are not loading the applet from localIP, then you will not be able to connect to it.
you may be able to get around this restriction by signing the applet.
Given that you are not using the Http Protocol, One assumes that the applet is loaded from another port other than 5555. If this is the case, the applet needs to be signed in order to do this functionality.

Categories

Resources