简体   繁体   中英

How can i use socket communication between java server and javascript client?

I'm trying to connect java Server and Javascript client with socket.io. When i see the debugger at browser, it looks like the data is being received, but i'm getting this error: "Reason: CORS header 'Access-Control-Allow-Origin' missing" and i am not being able to print data at client-side.

import...
public class MeuServerSocket {
    //initialize socket and input stream 
    private Socket socket = null;
    private ServerSocket server = null;
    private DataInputStream in = null;

    public MeuServerSocket(int port) {
        // starts server and waits for a connection 
        try {
            while(true){
            server = new ServerSocket(port);
            System.out.println("Server started");

            System.out.println("Waiting for a client ...");

            socket = server.accept();
            System.out.println("Client accepted");
            ObjectOutputStream saida = new ObjectOutputStream(socket.getOutputStream());
            saida.flush();
            // send available data from server to client
            saida.writeObject("Texto enviado 123...");

            // takes input from the client socket 
            in = new DataInputStream( 
                new BufferedInputStream(socket.getInputStream())); 

            String line = ""; 

            // reads message from client until "Over" is sent 
            boolean fim = false;
            while (!line.equals("Over") && !fim) 
            { 
                try
                { 
                    line = in.readUTF(); 
                    System.out.println(line); 

                } 
                catch(IOException i) 
                { 
                    fim = true;
                    System.out.println(i.toString());
                } 
            } 
            System.out.println("Closing connection");

            // close connection 
            socket.close();
            saida.close();
            in.close();
            }
        } catch (IOException i) {
            System.out.println(i);
        }catch(Exception e){
            System.out.println(e.toString());
        }
    }

    public static void main(String[] args) {
        MeuServerSocket server = new MeuServerSocket(5000);
    }
}

   var socket = io('http://localhost:5000');
   socket.on('connect', function () {
    socket.send('hi \nOver');

    socket.on('get', function (msg) {
      // my msg
      console.log('msg: '+msg)
    })

    socket.on('disconnect',()=>{
        console.log('disconnected')
    })
  })

When i look at Firefox network, i see that the data was sent inside one of the packages...

https://imgur.com/vDAS00B

TLDR: Use ws://... instead of http://... .

Details: https is used for HTTP protocol. In such case it is correct that browser first asks your server if CORS is allowed. You have not enabled CORS. That's why it is normal that browser refuses to send CORS request.

But you say you want to use Web Sockets. Then you should use ws:// , not http:// . For Web Sockets there is no CORS policy and browser will send your request without CORS restrictions.

The biggest issue I'm seeing here is a misunderstanding of socket.io. Socket.io for javascript is not compatible with the Socket library in java. The naming conventions can be confusing for sure.

socket.io is a library that is related to web sockets (ws://). It implements all the basic websocket features plus some bonuses.

What you have for your java code is a TCP socket server. While websockets and socket.io are built on TCP socket, you can not connect a socket.io client to a "naked" socket server.

SOLUTION: If your javascript is running from nodejs, you can use their net library found here . If you are running javascript from a webbrowser, than you are limited to websockets, which means you're going to change your java code to a websocket server. You can find a library for that somewhere online.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM