简体   繁体   English

如何在Java服务器和JavaScript客户端之间使用套接字通信?

[英]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. 我正在尝试将Java Server和Javascript客户端与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. 当我在浏览器上看到调试器时,似乎正在接收数据,但是我收到此错误:“原因:CORS标头'Access-Control-Allow-Origin'丢失”,我无法打印数据在客户端。

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... 当我查看Firefox网络时,我看到数据是在其中一个软件包中发送的。

https://imgur.com/vDAS00B https://imgur.com/vDAS00B

TLDR: Use ws://... instead of http://... . TLDR:使用ws://...而不是http://...

Details: https is used for HTTP protocol. 详细信息: https用于HTTP协议。 In such case it is correct that browser first asks your server if CORS is allowed. 在这种情况下,浏览器首先询问您的服务器是否允许CORS是正确的。 You have not enabled CORS. 您尚未启用CORS。 That's why it is normal that browser refuses to send CORS request. 这就是为什么浏览器拒绝发送CORS请求是正常的。

But you say you want to use Web Sockets. 但是您说您想使用Web套接字。 Then you should use ws:// , not http:// . 然后,您应该使用ws://而不是http:// For Web Sockets there is no CORS policy and browser will send your request without CORS restrictions. 对于Web套接字,没有CORS策略,浏览器将发送没有CORS限制的请求。

The biggest issue I'm seeing here is a misunderstanding of socket.io. 我在这里看到的最大问题是对socket.io的误解。 Socket.io for javascript is not compatible with the Socket library in java. javascript的Socket.io与Java中的Socket库不兼容。 The naming conventions can be confusing for sure. 命名约定肯定会造成混淆。

socket.io is a library that is related to web sockets (ws://). socket.io是一个与Web套接字(ws://)相关的库。 It implements all the basic websocket features plus some bonuses. 它实现了所有基本的websocket功能以及一些附加功能。

What you have for your java code is a TCP socket server. 您为Java代码准备的是一个TCP套接字服务器。 While websockets and socket.io are built on TCP socket, you can not connect a socket.io client to a "naked" socket server. 虽然websockets和socket.io是基于TCP套接字构建的,但是您不能将socket.io客户端连接到“裸”套接字服务器。

SOLUTION: If your javascript is running from nodejs, you can use their net library found here . 解决方案:如果您的JavaScript是从nodejs运行的,则可以使用在此处找到的它们的网络库。 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. 如果您是从Web浏览器运行javascript,则限于websockets,这意味着您要将Java代码更改为websocket服务器。 You can find a library for that somewhere online. 您可以在网上某个地方找到该图书馆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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