I am trying to establish a websocket connection in java to wss://data.tradingview.com/socket.io/websocket?from=chart%2F&date=2023_01_26-12_41&type=chart to acquire both historical and current chart data.
I have search and read through multiple posts and online resources and I am confused as to the correct procedure to connect to a websocket and acquire incoming data.
I found a post that is very close to what I'm trying to do that open a websocket and uses a ws as the target location. Here I've modified it slightly to implement the solution suggested.
import java.io.IOException;
import java.net.URI;
import javax.websocket.*;
#ClientEndpoint
public class ExampleTest2 {
Session session;
//Problem resolved, this original echo server is no longer operational
//private final static String url = "ws://echo.websocket.org:80";
private final static String url = "wss://websocket-echo.com:443/";
public static void main(String[] args) throws Exception, IOException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
System.out.println("connecting...");
container.connectToServer(ExampleTest2.class,
URI.create(url));
System.out.println("Press ENTER key to exit.");
System.in.read();
}
#OnMessage
public void newMessage(String message, Session session) {
System.out.println(message);
}
#OnOpen
public void newConnection(Session session) throws IOException {
this.session = session;
System.out.println("The connection has been started");
session.getBasicRemote().sendText("hello");
}
#OnClose
public void disconnection() {
System.out.println("The connection has been ended");
}
}
This is the error output I receive.
Exception in thread "main" java.lang.RuntimeException: Could not find an implementation class.
at javax.websocket.ContainerProvider.getWebSocketContainer(ContainerProvider.java:73)
at ExampleTest2.main(ExampleTest2.java:14)
I continued to search and found a post about that specific error. Here Their solution is to use a different external library. I was using javax.websocket-api-1.1.jar now I've switched to their recommendation of tyrus, tyrus-standalone-client-2.1.2
However it's still not connecting properly.
Exception in thread "main" jakarta.websocket.DeploymentException: Handshake error.
at org.glassfish.tyrus.client.ClientManager$3$1.run(ClientManager.java:658)
at org.glassfish.tyrus.client.ClientManager$3.run(ClientManager.java:696)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at org.glassfish.tyrus.client.ClientManager$SameThreadExecutorService.execute(ClientManager.java:849)
at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:118)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:493)
at org.glassfish.tyrus.client.ClientManager.connectToServer(ClientManager.java:299)
at ExampleTest2.main(ExampleTest2.java:19)
Caused by: org.glassfish.tyrus.core.HandshakeException: Response code was not 101: 200.
at org.glassfish.tyrus.client.TyrusClientEngine.processResponse(TyrusClientEngine.java:301)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleHandshake(GrizzlyClientFilter.java:323)
at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:292)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:88)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:246)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:178)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:118)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:96)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:51)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:510)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:82)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:83)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:101)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:535)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:515)
at java.base/java.lang.Thread.run(Thread.java:832)
At this point I am very much in the weeds and I'm not even sure if I'm going in the right direction anymore I'm just following rabbit hole after rabbit hole. At this point I'm trying to resolve indirect problems that I'm not even sure if it is required to accomplish my task of opening a socket and acquiring data.
Any help like code examples or learning material directly related to the task would be greatly appreciated.
I just found the solution. The original server in the code is no longer operation. I used this one instead "wss://websocket-echo.com:443/"
Related
I have used RMI in my code :
import java.rmi.*;
public interface AddServerIntf extends Remote {
double add(double d1,double d2) throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {
public AddServerImpl() throws RemoteException {
}
public double add(double d1,double d2) throws RemoteException {
return d1+d2;
}
}
import java.net.*;
import java.rmi.*;
public class AddServer {
public static void main(String args[]) {
try {
AddServerImpl addServerImpl=new AddServerImpl();
Naming.rebind("AddServer",addServerImpl);
} catch(Exception exc) {
System.out.println(exc);
}
}
}
import java.rmi.*;
public class AddClient {
public static void main(String args[]) {
try {
String Url="rmi://"+args[0]+"/AddServer";
AddServerIntf addServerIntf=(AddServerIntf)Naming.lookup(Url);
System.out.println("The first number is "+args[1]);
double d1=Double.valueOf(args[1]).doubleValue();
System.out.println("The second number is: "+args[2]);
double d2=Double.valueOf(args[2]).doubleValue();
System.out.println("The Sum is: "+addServerIntf.add(d1,d2));
} catch(Exception exc) {
System.out.println(exc);
}
}
}
These are 4 .java files written.
Next i compile all these files.Then I create a stub using rmic AddServerImpl. After that i start rmi registry on server side using start rmiregistry. Then i start server using java AddServer and finally client using java AddClient 27.60.200.80 5 9.
But nothing happens
Exception that is thrown on client side is java.net.ConnectException : connection timed out : connect
What is the reason and how can i solve this?
On client machine these are the following .class files AddClient.class AddServerImpl.class AddServerImpl_Stub.class and on server side AddServer.class AddServerImpl.class AddServerImpl_Stub.class AddServerIntf.class
The error message says it all: your connection timed out. This means your request did not get a response within some (default) timeframe. The reasons that no response was received is likely to be one of:
a) The IP/domain or port is incorrect
b) The IP/domain or port (i.e service) is down
c) The IP/domain is taking longer than your default timeout to respond
d) You have a firewall that is blocking requests or responses on whatever port you are using
e) You have a firewall that is blocking requests to that particular host
f) Your internet access is down
Note that firewalls and port or IP blocking may be in place by your ISP
Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a.
C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name.
Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.
Exception : java.net.ConnectException
This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:
Too many requests overloading the server
Request packet loss because of wrong network configuration or line overload
Sometimes firewall consume request packet before sever getting
Also depends on thread connection pool configuration and current status of connection pool
Response packet lost during transition
If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:
NSLOOKUP fabrikam.com
Test-NetConnection <IP returned from NSLOOKUP> -port 389
I'm trying to implement a simple websocket client in java using the javax websocket library, here's my code:
import java.io.IOException;
import java.net.URI;
import javax.websocket.*;
#ClientEndpoint
public class Client {
Session session;
private final static String url = "ws://echo.websocket.org";
public static void main(String[] args) throws Exception, IOException {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
System.out.println("connecting...");
container.connectToServer(Client.class,
URI.create(url));
}
#OnMessage
public void newMessage(String message, Session session) {
System.out.println(message);
}
#OnOpen
public void newConnection(Session session) throws IOException {
this.session = session;
System.out.println("The connection has been started");
session.getBasicRemote().sendText("hello");
}
#OnClose
public void disconnection() {
System.out.println("The connection has been ended");
}
}
As you can see in the #OnOpen annotation i try to send the "Hello" string message and on the #OnMessage i just want print the message in the console.
I can run the code without errors, but i just got the "connecting..." print so can anyone explain what is wrong with the code?
Note: i added the org.glassfish.tyrus libraries that's needed to work with the javax.websocket to the referenced libraries as well
I'm newbie in Java so sorry for the dumb question
Your program is exiting immediately after calling container.connectToServer(...) so your newConnection(...) and newMessage(...) functions never get a chance to run. You need to keep your program running after the call to container.connectToServer(...). You can do this by, for example, adding the following code after the container.connectToServer(...) line which will cause the program to wait for the ENTER key to be pressed:
System.out.println("Press ENTER key to exit.");
System.in.read();
After making that change, your program worked correctly on my computer and displayed the "The connection has been started" and "hello" messages.
It seems like a duplicate question of how to kill a process already running on that port, but it is a different question. When I killed the process and restart it, it still gives me that error message, seems like Netbeans has a problem, and the error message got stuck and keeps appearing even when the port is not in use.
I've used the tool at : http://www.yougetsignal.com/tools/open-ports/ to check the port : 6600
Here is what it says :
My code looks like the following :
import java.io.*;
import java.util.*;
import com.sun.net.httpserver.*;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import Utility.*;
public class Http_Server
{
static int Port=6600,Thread_Count=50,Resume_Count=0; // 8080
InetSocketAddress addr;
HttpServer server;
static String App_Id="Resume_App";
static Resume_Loader Resume_loader;
static Get_Time Timer=new Get_Time();
static Vector<String> Current_Keywords_Vector=new Vector();
static boolean Debug_B=true;
public Http_Server(int Port)
{
if (Port>-1) this.Port=Port;
Srart_Server();
}
void Srart_Server()
{
try
{
Resume_loader=new Resume_Loader();
addr=new InetSocketAddress(Port);
server=HttpServer.create(addr,0); // Line : 34
server.createContext("/"+App_Id,new MyHandler(server));
server.setExecutor(Executors.newCachedThreadPool());
server.start();
Out("Server is listening on port : "+Port);
}
catch (Exception e)
{
Resume_App.Save_To_Log(e.toString()+"\n"+Tool_Lib_Simple.Get_Stack_Trace(e));
e.printStackTrace();
Out(e.toString());
}
}
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
public static void main(String[] args) { Http_Server Demo=new Http_Server(-1); }
}
It was running fine yesterday, but this morning I changed :
InetSocketAddress addr; to static InetSocketAddress addr;
HttpServer server; to static HttpServer server;
When I ran it, I got the following error message :
Server is listening on port : 6600
java.net.BindException: Address already in use: bind
at sun.nio.ch.Net.bind0(Native Method)
at sun.nio.ch.Net.bind(Net.java:437)
at sun.nio.ch.Net.bind(Net.java:429)
at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
at sun.net.httpserver.ServerImpl.<init>(ServerImpl.java:100)
at sun.net.httpserver.HttpServerImpl.<init>(HttpServerImpl.java:50)
at sun.net.httpserver.DefaultHttpServerProvider.createHttpServer(DefaultHttpServerProvider.java:35)
at com.sun.net.httpserver.HttpServer.create(HttpServer.java:130)
at Http_Server.Srart_Server(Http_Server.java:34)
at Http_Server.<init>(Http_Server.java:24)
at Http_Server.main(Http_Server.java:51)
Then I realize if they are static, they might keep them selves in memory and occupy the port, so I changed them back to non-static like the above code. But now when I run it, the error message keeps appearing, and in Netbeans there is a "notification" saying something like : "package-info.class is in wrong place, delete it or put it in the right sub directory ..." don't remember the exact wording. But when I open the url, the web page works fine as if there is no error message, and when I stop the server the page won't appear as it supposed to be.
So it seems like a Netbeans 8.0.2 malfunctioning, but I don't know how to make the error message not appear, or as it suggested how to delete "package-info.class" or put it into the correct sub dir, I can't even find where it is, how to fix it ?
Regarding :
there is a "notification" saying something like : "package-info.class is in wrong place, delete it or put it in the right sub directory ..." don't remember the exact wording
Please make it happen again and copy and paste or screenshot the exact wording into your question.
I think it would be much better to explicitly call shutdown() on your ExecutiveService and stop(1) on your HttpServer rather than hoping garbage collection will do it. And it would allow you to control print some messages confirming it.
eg.
InetSocketAddress addr = new InetSocketAddress(6600);
ExecutorService es = Executors.newCachedThreadPool();
HttpServer server = HttpServer.create(addr, 0);;
server.createContext("/foo", new HttpHandler() {
#Override
public void handle(HttpExchange he) throws IOException {
String response = "My Response";
he.sendResponseHeaders(200, response.length());
OutputStream os = he.getResponseBody();
os.write(response.getBytes());
os.close();
}
});
server.setExecutor(es);
server.start();
System.out.println("Press enter to stop server.");
// block waiting for user to press enter.
System.in.read();
System.out.println("Shutting down");
server.stop(1);
es.shutdownNow();
System.out.println("should be shutdown now.");
Also at the bottom of netbeans there is a status line.
If you see this you need to click the little x to stop whatever process you launched but perhaps forgot about.
I am trying to create a Java Application Client project that sends a JMS message to a queue on a Glassfish server.
The problem is that after the app sends the message, it hangs when it's supposed to exit. The message is transmitted successfully, but for some reason the app doesn't exit. I have tried to debug the application, and I can step trough it all the way to the end of static void main, and that's where it hangs.
Here is the code:
import javax.jms.*;
import javax.naming.InitialContext;
public class Main {
public void SendMessage() throws Exception {
InitialContext ctx = new InitialContext();
ConnectionFactory cf = (ConnectionFactory) ctx.lookup("jms/TestFactory");
Queue queue = (Queue)ctx.lookup("jms/TestQueue");
Connection conn = cf.createConnection();
Session s = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer prod = s.createProducer(queue);
TextMessage txt = s.createTextMessage("testing");
prod.send(txt);
prod.close();
s.close();
conn.close();
}
public static void main(String[] args) throws Exception {
Main m = new Main();
m.SendMessage();
}
public Main() {
super();
}
}
How can I make it stop hanging?
It's been a bug in Glassfish for a long time.
There is a bug recorded here (reported back in version 9 of Sun App Server, predating Glassfish), but I suspect there will be lots of duplicate reports:
http://java.net/jira/browse/GLASSFISH-1429
My only known fix is to System.exit(0) (in a finally block), which closes all threads.
Horrible, yes.
Good call on the thread dump. Try issuing a Conn.stop(). It seems the JMS client still has non daemon threads running
I am trying to get a rmi connection going. I have ran into many security issues but have been unable to find a way past all this. I execute my jar file with:
java -Djava.security.policy=java.security.AllPermission -jar "myjarfile"
The code I have been using to create this is:
public class server
{
public static void main(String args[])throws Exception
{
if (System.getSecurityManager() == null)
System.setSecurityManager ( new RMISecurityManager() {
public void checkConnect (String host, int port) {}
public void checkConnect (String host, int port, Object context) {}
});
try
{
sampleserverimpl server = new sampleserverimpl();
System.out.println("SERVER IS WAITING");
LocateRegistry.createRegistry(2020);
//Runtime.getRuntime().exec("rmiregistry 2020");
Naming.rebind("//localhost:2020/SERVER", server);
}
catch(Exception e)
{
System.out.println(e);
}
}
};
The error trace I am receiving is:
Exception in thread "RMI TCP Connection(idle)" java.security.AccessControlExcept
ion: access denied (java.net.SocketPermission 127.0.0.1:31199 accept,resolve)jav
a.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
java.io.EOFException
I have tried different ways to get around this, can anyone see the issue here?
Thanks
-Djava.security.policy accepts a URL which points to a policy file which in turn contains the permissions. So you should have: -Djava.security.policy=/some/path/my.policy as the JVM argument where the my.policy file contains:
grant {
permission java.security.AllPermission;
};
Also, in order to avoid the NULL check present in your code and the manual creation of a SecurityManager, you can request a SecurityManager be automatically installed for your application by passing the JVM switch: -Djava.security.manager.
Your final JVM invocation should look like:
java -Djava.security.manager -Djava.security.policy=/some/path/my.policy
This is two separate exceptions. The first is a permission problem. The second one, the EOFException, could have any of a number of causes. I would need to see java -version and the complete stack trace to assist further.