处理 - 如何将数据(通过 websockets?)发送到 javascript 应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:37:21  来源:igfitidea点击:

Processing - how to send data (through websockets?) to javascript application

javascriptwebsocketprocessing

提问by Slevin

I'm playing around with processing and wonder, if i can send data from processing to a javascript app. Is there any possibility to create a (e.g. websocket) server with processing?

我正在处理处理并想知道是否可以将处理中的数据发送到 javascript 应用程序。是否有可能创建一个(例如 websocket)服务器进行处理?

Thanks in advance!

提前致谢!

回答by George Profenza

I've tried Java WebSocketsin eclipse for desktop(with or without extending PApplet) and it works on Android as well. If you want to use the library in Processing you need to do this:

我已经在 eclipse 中为桌面尝试了Java WebSockets(有或没有扩展 PApplet),它也适用于 Android。如果要在 Processing 中使用该库,则需要执行以下操作:

  1. create a folder named java_websocketin Documents/Processing/libraries
  2. Inside the newly created java_websocket folder create another folder named libraryand drop java_websocket.jar there
  3. Restart Processing and start using the library (sketch > import library should list java_websocket now)
  1. 在 Documents/Processing/libraries 中创建一个名为java_websocket的文件夹
  2. 在新创建的 java_websocket 文件夹中创建另一个名为library 的文件夹并将java_websocket.jar 放在那里
  3. 重新启动处理并开始使用库(草图 > 导入库现在应该列出 java_websocket)

And here's the project sample code in processing: The server:

这是正在处理的项目示例代码: 服务器:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Collection;

import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

void setup(){
  new ServerThread().start();
}
//create a separate thread for the server not to freeze/interfere with Processing's default animation thread
public class ServerThread extends Thread{
  @Override
  public void run(){
    try{
          WebSocketImpl.DEBUG = true;
          int port = 8887; // 843 flash policy port
          try {
            port = Integer.parseInt( args[ 0 ] );
          } catch ( Exception ex ) {
          }
          ChatServer s = new ChatServer( port );
          s.start();
          System.out.println( "ChatServer started on port: " + s.getPort() );

          BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) );
          while ( true ) {
            String in = sysin.readLine();
            s.sendToAll( in );
          }
        }catch(IOException e){
          e.printStackTrace();
        }  
  }
}
public class ChatServer extends WebSocketServer {

  public ChatServer( int port ) throws UnknownHostException {
    super( new InetSocketAddress( port ) );
  }

  public ChatServer( InetSocketAddress address ) {
    super( address );
  }

  @Override
  public void onOpen( WebSocket conn, ClientHandshake handshake ) {
    this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
    System.out.println( conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!" );
  }

  @Override
  public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
    this.sendToAll( conn + " has left the room!" );
    System.out.println( conn + " has left the room!" );
  }

  @Override
  public void onMessage( WebSocket conn, String message ) {
    this.sendToAll( message );
    System.out.println( conn + ": " + message );
  }

  @Override
  public void onError( WebSocket conn, Exception ex ) {
    ex.printStackTrace();
    if( conn != null ) {
      // some errors like port binding failed may not be assignable to a specific websocket
    }
  }

  /**
   * Sends <var>text</var> to all currently connected WebSocket clients.
   * 
   * @param text
   *            The String to send across the network.
   * @throws InterruptedException
   *             When socket related I/O errors occur.
   */
  public void sendToAll( String text ) {
    Collection<WebSocket> con = connections();
    synchronized ( con ) {
      for( WebSocket c : con ) {
        c.send( text );
      }
    }
  }
}

a test client:

测试客户端:

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.java_websocket.WebSocketImpl;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.drafts.Draft_10;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.drafts.Draft_75;
import org.java_websocket.drafts.Draft_76;
import org.java_websocket.handshake.ServerHandshake;

void setup(){
  WebSocketImpl.DEBUG = true;
  new ChatClient( "ws://localhost:8887" );
}

public class ChatClient extends JFrame implements ActionListener {
  private static final long serialVersionUID = -6056260699202978657L;

  private final JTextField uriField;
  private final JButton connect;
  private final JButton close;
  private final JTextArea ta;
  private final JTextField chatField;
  private final JComboBox draft;
  private WebSocketClient cc;

  public ChatClient( String defaultlocation ) {
    super( "WebSocket Chat Client" );
    Container c = getContentPane();
    GridLayout layout = new GridLayout();
    layout.setColumns( 1 );
    layout.setRows( 6 );
    c.setLayout( layout );

    Draft[] drafts = { new Draft_17(), new Draft_10(), new Draft_76(), new Draft_75() };

    draft = new JComboBox( drafts );
    c.add( draft );

    uriField = new JTextField();
    uriField.setText( defaultlocation );
    c.add( uriField );

    connect = new JButton( "Connect" );
    connect.addActionListener( this );
    c.add( connect );

    close = new JButton( "Close" );
    close.addActionListener( this );
    close.setEnabled( false );
    c.add( close );

    JScrollPane scroll = new JScrollPane();
    ta = new JTextArea();
    scroll.setViewportView( ta );
    c.add( scroll );

    chatField = new JTextField();
    chatField.setText( "" );
    chatField.addActionListener( this );
    c.add( chatField );

    java.awt.Dimension d = new java.awt.Dimension( 300, 400 );
    setPreferredSize( d );
    setSize( d );

    addWindowListener( new java.awt.event.WindowAdapter() {
      @Override
      public void windowClosing( WindowEvent e ) {
        if( cc != null ) {
          cc.close();
        }
        dispose();
      }
    } );

    setLocationRelativeTo( null );
    setVisible( true );
  }

  public void actionPerformed( ActionEvent e ) {

    if( e.getSource() == chatField ) {
      if( cc != null ) {
        cc.send( chatField.getText() );
        chatField.setText( "" );
        chatField.requestFocus();
      }

    } else if( e.getSource() == connect ) {
      try {
        // cc = new ChatClient(new URI(uriField.getText()), area, ( Draft ) draft.getSelectedItem() );
        cc = new WebSocketClient( new URI( uriField.getText() ), (Draft) draft.getSelectedItem() ) {

          @Override
          public void onMessage( String message ) {
            ta.append( "got: " + message + "\n" );
            ta.setCaretPosition( ta.getDocument().getLength() );
          }

          @Override
          public void onOpen( ServerHandshake handshake ) {
            ta.append( "You are connected to ChatServer: " + getURI() + "\n" );
            ta.setCaretPosition( ta.getDocument().getLength() );
          }

          @Override
          public void onClose( int code, String reason, boolean remote ) {
            ta.append( "You have been disconnected from: " + getURI() + "; Code: " + code + " " + reason + "\n" );
            ta.setCaretPosition( ta.getDocument().getLength() );
            connect.setEnabled( true );
            uriField.setEditable( true );
            draft.setEditable( true );
            close.setEnabled( false );
          }

          @Override
          public void onError( Exception ex ) {
            ta.append( "Exception occured ...\n" + ex + "\n" );
            ta.setCaretPosition( ta.getDocument().getLength() );
            ex.printStackTrace();
            connect.setEnabled( true );
            uriField.setEditable( true );
            draft.setEditable( true );
            close.setEnabled( false );
          }
        };

        close.setEnabled( true );
        connect.setEnabled( false );
        uriField.setEditable( false );
        draft.setEditable( false );
        cc.connect();
      } catch ( URISyntaxException ex ) {
        ta.append( uriField.getText() + " is not a valid WebSocket URI\n" );
      }
    } else if( e.getSource() == close ) {
      cc.close();
    }
  }


}

That's pretty much pasted Java code which is verbose. But it should be easy to make some helper/wrapper classes if needed.

这几乎是粘贴的 Java 代码,非常冗长。但是如果需要的话,制作一些帮助器/包装器类应该很容易。

Doing a quick search returns these handy results:

进行快速搜索会返回这些方便的结果:

UPDATE

更新

I've recently been introduced to a new Websockets library called spacebrewwhich is great for your inquiry, especially since they seem to have wrapped the java_websocket nicely behind the scenes.

我最近被介绍到一个名为spacebrew的新 Websockets 库,它非常适合您的查询,特别是因为它们似乎在幕后很好地包装了 java_websocket。

Now you use this as any other Processing library, usage is greatly simplified(not java library experience needed, just Processing will do) and examples are great!

现在您可以将它用作任何其他处理库,用法大大简化(不需要 java 库经验,只需处理即可)并且示例很棒!

I got introduced to this through another questionwhich allowed me to find out that it actually it works out of the box on your Android Device as well out of the box(just need to check the INTERNET box). How awesome is that ?

我是通过另一个问题了解到这一点的,这让我发现它实际上在您的 Android 设备上开箱即用,开箱即用(只需要检查互联网框)。那有多棒?

Getting all that sweet websocket action going on like it ain't no thing and bonus, it's android supported.

进行所有那些甜蜜的 websocket 操作,就像它不是什么东西和奖励一样,它是 android 支持的。

Quickly prototype on your desktop, then get your project working from your pocket.

在您的桌面上快速制作原型,然后从您的口袋中开始您的项目。

spacebrew demo 1

spacebrew 演示 1

spacebrew demo 2

太空酿造演示 2

spacebrew demo 3

太空酿造演示 3

Spacebrew ? Processing

太空酿?加工