简体   繁体   English

使用ColdFusion的简单TCP / IP套接字通信

[英]Simple TCP/IP socket communication using ColdFusion

I've done some searching and it doesn't seem like there is much in the way of success in establishing a tcp/ip socket connection successfully via Coldfusion. 我已经进行了一些搜索,但似乎似乎没有太多成功通过Coldfusion成功建立tcp / ip套接字连接的方法。 I'm trying to act as a simple client and send a string over and get a response. 我试图充当一个简单的客户端,并发送一个字符串并获得响应。 Adobe's EventGateway requires server-side setup, which I can't touch, but also appears to be a listener only (according to Adobe's doc, "It can send outgoing messages to existing clients, but cannot establish a link itself."). Adobe的EventGateway需要服务器端设置,这是我无法触及的,但似乎仅是侦听器(根据Adobe的文档,“它可以将传出的消息发送到现有客户端,但不能自己建立链接。”)。

There is another example on SO/cflib.org that is the prevailing post over the web invoking Java objects, but I'm not succeeding with it and it seems pretty much everyone else has some degree of trouble with it. SO / cflib.org上还有另一个示例,它是Web上普遍使用Java对象的帖子,但我没有成功,而且似乎其他所有人都对此有一定的麻烦。 In my attempts, I can get it to init/connect a socket, but nothing else. 在我的尝试中,我可以使用它来初始化/连接套接字,但没有别的。 If I try to send a string, the CF page loads fine but the server side seemingly never sees anything (but will log or note a connection/disconnection). 如果我尝试发送字符串,则CF页可以很好地加载,但是服务器端看似看不到任何东西(但会记录或记录连接/断开连接)。 If I try to read a response, the page will never load. 如果我尝试读取响应,则该页面将永远不会加载。 If I close the server while it's trying, it will show a connection reset while trying readLine(). 如果在尝试关闭服务器时将其关闭,则在尝试readLine()时它将显示连接重置。 I have tried this with an in-house app as well as a simple Java socket listener that will send a message on connect and should echo anything sent. 我已经使用内部应用程序以及一个简单的Java套接字侦听器进行了尝试,该侦听器将在connect上发送一条消息,并应回显所发送的任何内容。

Is this just not a job for CF? 这不是CF的工作吗? If not, any other simple suggestions/examples from the jQuery/Ajax realm? 如果不是,是否有来自jQuery / Ajax领域的其他简单建议/示例?

Java listener app: Java侦听器应用程序:

package blah;

import java.awt.Color;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;

import java.io.*;
import java.net.*;

class SocketServer extends JFrame
    implements ActionListener {

/**
 * 
 */
private static final long serialVersionUID = 1L;
JButton button;
   JLabel label = new JLabel("Text received over socket:");
   JPanel panel;
   JTextArea textArea = new JTextArea();
   ServerSocket server = null;
   Socket client = null;
   BufferedReader in = null;
   PrintWriter out = null;
   String line;

   SocketServer(){ //Begin Constructor
     button = new JButton("Click Me");
     button.addActionListener(this);

     panel = new JPanel();
     panel.setLayout(new BorderLayout());
     panel.setBackground(Color.white);
     getContentPane().add(panel);
     panel.add("North", label);
     panel.add("Center", textArea);
     panel.add("South", button);

   } //End Constructor

  public void actionPerformed(ActionEvent event) {
     Object source = event.getSource();

     if(source == button){
         textArea.setText(line);
     }
  }

  public void listenSocket(){

    try{
      server = new ServerSocket(4444); 
    } catch (IOException e) {
     System.out.println("Could not listen on port 4444");
      System.exit(-1);
    }

    try{
      client = server.accept();
 //Show connection status in text box, and send back to client
      line = " Connected ";
      out.println(line);
      textArea.setText(line);
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }

    try{
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      out = new PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }

    while(true){
      try{
//Try to concatenate to see if line is being changed and we're just not seeing it, show in textbox
        line = line + " " + in.readLine();
        textArea.setText(line);
//Send data back to client
        out.println(line);
      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
      }
    }
  }

  protected void finalize(){
//Clean up 
     try{
        in.close();
        out.close();
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close.");
        System.exit(-1);
    }
  }

  public static void main(String[] args){
        SocketServer frame = new SocketServer();
    frame.setTitle("Server Program");
        WindowListener l = new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                        System.exit(0);
                }
        };
        frame.addWindowListener(l);
        frame.pack();
        frame.setVisible(true);
    frame.listenSocket();
  }
}

CF Simple Send (minus HTML header/footer, IP to be hard-coded, port on simple listener = 4444): CF简单发送(减去HTML标头/页脚,要硬编码的IP,简单侦听器上的端口= 4444):

<cfset sock = createObject( "java", "java.net.Socket" )>
<cfset sock.init( "ip.ip.ip.ip", 4444)>

<cfset streamOut = sock.getOutputStream()>

<cfset output = createObject("java", "java.io.PrintWriter").init(streamOut)>
<cfset streamOut.flush()>

<cfset output.println("Test Me")>
<cfset output.println()>

<cfset streamOut.flush()>

<cfset sock.shutdownOutput()>
<cfset sock.close()>

Simple CF Read (again, minus header/footer template, IP of server to be hard-coded, port 4444) 简单的CF读取(再次,减去页眉/页脚模板,要进行硬编码的服务器IP,端口4444)

<cfset sock = createObject( "java", "java.net.Socket" )>
<cfset sock.init( "ip.ip.ip.ip", 4444)>

<cfset streamInput = sock.getInputStream()>
<cfset inputStreamReader= createObject( "java", "java.io.InputStreamReader").init(streamInput)>

<cfset input = createObject( "java", "java.io.BufferedReader").init(InputStreamReader)>

<cfset result = input.readLine()>

<cfset sock.shutdownInput()>
<cfset sock.close()>

I've tried adding some sleeps here and there and also have tried a send not using PrintWriter/using just ObjectOutputStream and writeObject() , but same behavior. 我试过在这里和那里添加一些睡眠,也尝试过不使用PrintWriter /仅使用ObjectOutputStream和writeObject()进行发送,但是行为相同。 Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

This is going to be a very challenging process to implement in ColdFusion, even when taking advantage of Java, for the simple reason of: 即使在利用Java的情况下,在ColdFusion中实现这也将是一个非常具有挑战性的过程,原因很简单:

Socket communication is real-time, while web requests have finite starting and stopping points. 套接字通信是实时的,而Web请求具有有限的起点和终点。

For example, when you make a ColdFusion template request, everything (variables, shared memory, object instantiation, etc.) lives within the context of the page request--and (barring a few caveats) dies when the page request ends. 例如,当您发出ColdFusion模板请求时,所有内容(变量,共享内存,对象实例化等)都存在于页面请求的上下文中,并且(除非有一些警告)在页面请求结束时消失。 So, let's assume for the moment that you had a CFML template that performed the following tasks when requested: 因此,让我们暂时假设您有一个CFML模板,该模板在被请求时执行以下任务:

  1. Opened a socket. 打开一个插座。
  2. Established a connection to a remote ip:port. 建立与远程ip:port的连接。
  3. Listened for a response. 听了回应。
  4. Printed that response to the browser. 将响应打印到浏览器。

Let's assume further that your code is up-and-running, tested, and working. 让我们进一步假设您的代码是运行,测试和运行的。 You are able to open the socket, connect to a remote ip and port (you actually see the incoming request on the remote server, and can confirm this) and for all intents and purposes...your connection is good. 您可以打开套接字,连接到远程ip和端口(您实际上在远程服务器上看到传入的请求,并且可以确认这一点),并且出于所有目的和目的……您的连接良好。

Then, 10 minutes after you executed your CFML page, the remote server sent a string of text over the connection... 然后,在执行CFML页面10分钟后,远程服务器通过连接发送了文本字符串。

...there is nothing on your CFML end that is alive and awaiting that response, ready to print it to the browser. ...在您的CFML端,没有任何东西处于活动状态并且正在等待该响应,可以将其打印到浏览器中。 The objects that you instantiated, used to open a socket, and connect...have all gone away, when the CFML template request ended. 当CFML模板请求结束时,您实例化,用于打开套接字以及进行连接的对象都消失了。

This is why (as stated above) when you tried to "read a response", you observed that the page never loaded. 这就是为什么(如上所述)尝试“读取响应”时观察到页面从未加载的原因。 What's happening is that ColdFusion is being told "stand by please, we could actually maybe possibly get some data over this socket"...so it blocks the web request from ending and waits...which manifests to the user as what appears to be a "hung" web page. 发生的是,ColdFusion被告知“请稍等,实际上我们可能可以通过此套接字获取一些数据” ...因此它阻止了Web请求的结束并等待...这在用户看来是是一个“挂”网页。

The nature of real-time socket communication is that it is connected and listening, waiting for a response...and unfortunately, a running web-page cannot run (and 'wait') forever, it will eventually timeout. 实时套接字通信的本质是连接,监听,等待响应……不幸的是,正在运行的网页无法永远运行(和“等待”),最终将超时。

The bottom line is that while Java will allow you to open / connect / send / receive / close raw sockets, doing so from within the context of a CFML page may not be the approach you are ultimately looking for. 最重要的是,尽管Java允许您打开/连接/发送/接收/关闭原始套接字,但是从CFML页面的上下文中执行此操作可能并不是您最终要寻找的方法。

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

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