使用ColdFusion的简单TCP / IP套接字通信 [英] Simple TCP/IP socket communication using ColdFusion

查看:146
本文介绍了使用ColdFusion的简单TCP / IP套接字通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经做了一些搜索,似乎没有太多的成功建立tcp / ip套接字连接成功通过Coldfusion的方式。我试图作为一个简单的客户端,发送一个字符串,并得到一个响应。 Adobe的EventGateway需要服务器端设置,我不能接触,但似乎只是一个侦听器(根据Adobe的文档,它可以发送传出消息到现有客户端,但不能建立链接本身。) / p>

还有另一个例子,SO / cflib.org是Web上调用Java对象的主流文章,但我不是成功的,它似乎几乎每个人否则有一定程度的麻烦。在我的尝试,我可以得到它init /连接一个套接字,但没有别的。如果我尝试发送一个字符串,CF页面加载正常,但服务器端似乎从来没有看到任何东西(但会记录或注意连接/断开连接)。如果我尝试读取响应,页面将永远不会加载。如果我在尝试时关闭服务器,它将尝试readLine()时显示连接重置。我已经尝试这与内部的应用程序,以及一个简单的Java套接字侦听器,将发送消息连接,应回应发送的任何东西。



这只是不是CF的工作?如果没有,从jQuery / Ajax领域的任何其他简单的建议/示例?



Java侦听器应用程序:

  package blah; 

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

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

类SocketServer扩展JFrame
实现ActionListener {

/ **
*
* /
private static final long serialVersionUID = 1L;
JButton按钮;
JLabel label = new JLabel(通过套接字接收文本);
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构造函数

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();
//在文本框中显示连接状态,并发回客户端
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 {
//尝试连接以查看行是否正在更改,我们只是看不到它, in textbox
line = line ++ in.readLine();
textArea.setText(line);
//将数据发送回客户端
out.println(line);
} catch(IOException e){
System.out.println(Read failed);
System.exit(-1);
}
}
}

protected void finalize(){
//清理
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简单发送(减去HTML页眉/硬编码,简单侦听器端口= 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()>

简单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()>

我试过在这里和那里添加一些睡眠,并尝试了一个不使用PrintWriter /只是ObjectOutputStream和writeObject(),但是行为相同。任何帮助将非常感谢。谢谢!

解决方案

这将是一个非常具有挑战性的过程在ColdFusion中实现,即使利用Java,简单的原因:



套接字通信是实时的,而Web请求具有有限的起点和终点。



例如,当你创建一个ColdFusion模板请求时,一切(变量,共享内存,对象实例化等)都存在于页面请求的上下文中 - 并且(禁止几个警告)当页面请求结束时。所以,让我们假设你有一个CFML模板,当请求时执行以下任务:


  1. 打开了一个套接字。

  2. 已建立与远程ip:端口的连接。

  3. 已听取响应。

  4. 浏览器。

让我们进一步假设您的代码是正常运行,测试和工作。您可以打开套接字,连接到远程ip和端口(您实际上看到远程服务器上的传入请求,并且可以确认这一点)以及所有意图和目的...您的连接是好的。



然后,在执行CFML页面10分钟后,远程服务器通过连接发送一个文本字符串...



...在CFML端没有什么是活的,等待响应,准备打印到浏览器。



这就是为什么(如上所述),当你在CFML模板请求结束时,你实例化,用于打开一个套接字和连接...的对象全部消失了。上面)当你试图读取响应,你观察到页面从未加载。发生了什么是ColdFusion被告知支持请,我们可能实际上可能获得一些数据通过这个套接字...所以它阻止Web请求结束和等待...这显示给用户,成为挂起网页。



实时套接字通信的性质是它是连接和侦听,等待响应...而不幸的是,运行的网页不能运行



底线是,虽然Java将允许你打开/连接/发送/接收/关闭原始套接字,做所以从CFML页面的上下文可能不是你最终寻找的方法。


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. 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.").

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. 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). 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(). 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.

Is this just not a job for CF? If not, any other simple suggestions/examples from the jQuery/Ajax realm?

Java listener app:

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):

<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)

<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. 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:

Socket communication is real-time, while web requests have finite starting and stopping points.

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. So, let's assume for the moment that you had a CFML template that performed the following tasks when requested:

  1. Opened a socket.
  2. Established a connection to a remote 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.

Then, 10 minutes after you executed your CFML page, the remote server sent a string of text over the connection...

...there is nothing on your CFML end that is alive and awaiting that response, ready to print it to the browser. The objects that you instantiated, used to open a socket, and connect...have all gone away, when the CFML template request ended.

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.

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.

这篇关于使用ColdFusion的简单TCP / IP套接字通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆