trinopoty / socket.io-server-java

Socket.IO Server Library for Java
Other
179 stars 50 forks source link

How to support cross-origin websocket request from 127.0.0.1 with different ports? #46

Closed chenzx closed 1 year ago

chenzx commented 1 year ago

I'm using socket.io-server-java in a android app(which means, running it in a background Thread in a Service) I use the tcp listen port 9999, and setup adb forward:

adb forward tcp:9999 tcp:9999

Then a use a web page client from local host with port 10000, but the web client cannot connect with server side report error:

I/System.out: 400 null HTTP/1.1
I/System.out: Date: Fri, 24 Mar 2023 08:39:51 GMT
I/System.out: Access-Control-Allow-Origin: http://127.0.0.1:10000
I/System.out: Access-Control-Allow-Credentials: true
I/System.out: Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
I/System.out: Access-Control-Allow-Headers: origin, content-type, accept
I/System.out: Content-Type: application/json;charset=utf-8

It seems the cross-origin is not defaultly supported. How can I enable CORS?

chenzx commented 1 year ago

This is the code i tried:

        FilterHolder holder = new FilterHolder(CrossOriginFilter.class);
        holder.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        holder.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        holder.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,OPTIONS,DELETE,PUT,HEAD");
        holder.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin,Authorization");
        holder.setInitParameter(CrossOriginFilter.ALLOW_CREDENTIALS_PARAM, "true");
        holder.setInitParameter(CrossOriginFilter.EXPOSED_HEADERS_PARAM, "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin,Location,Accept-Content-Encoding");
        holder.setName("cross-origin");
        FilterMapping fm = new FilterMapping();
        fm.setFilterName("cross-origin");
        fm.setPathSpec("/*");
        ServletHandler handler = new ServletHandler();
        handler.addFilter(holder, fm);
...
handlerList.setHandlers(new Handler[] { handler, servletContextHandler });

CrossOriginFilter is not contained in deps, so i copied one from https://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-servlets/src/main/java/org/eclipse/jetty/servlets/CrossOriginFilter.java

However, the server side and client still report a 404 error.

trinopoty commented 1 year ago

Hi, Please take a look at the setAllowedCorsOrigins method in EngineIoServerOptions class. You may need to tweak some config in your webserver to get websocket working since that's outside the control of socket.io/engine.io