views:

420

answers:

2

I tried the below function.This function allows ColdFusion developers to connect to remote hosts through the TCP/IP protocol and transmit messages. Very useful for implementing chat rooms, integrate with third party applications such as merchant carts etc.

<cffunction name="easySocket" access="private" returntype="any" hint="Uses Java Sockets to connect to a remote socket over TCP/IP" output="false">

    <cfargument name="host" type="string" required="yes" default="localhost" hint="Host to connect to and send the message">
    <cfargument name="port" type="numeric" required="Yes" default="8080" hint="Port to connect to and send the message">
    <cfargument name="message" type="string" required="yes" default="" hint="The message to transmit">

    <cfset var result = "">
    <cfset var socket = createObject( "java", "java.net.Socket" )>
    <cfset var streamOut = "">
    <cfset var output = "">
    <cfset var input = "">

    <cftry>
        <cfset socket.init(arguments.host,arguments.port)>
        <cfcatch type="Object">
            <cfset result = "#cfcatch.Message#<br>Could not connected to host <strong>#arguments.host#</strong>, port <strong>#arguments.port#</strong>.">
            <cfreturn result>
        </cfcatch>
    </cftry>

    <cfif socket.isConnected()>
        <cfset streamOut = socket.getOutputStream()>

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

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

        <cfset output.println(arguments.message)>
        <cfset output.println()>
        <cfset output.flush()>

        <cfset result=input.readLine()>
        <cfset socket.close()>
    <cfelse>
        <cfset result = "Could not connected to host <strong>#arguments.host#</strong>, port <strong>#arguments.port#</strong>.">
    </cfif>

    <cfreturn result>
</cffunction>

<cfoutput>#easySocket('192.168.0.55','8080','Hello from ColdFusion')#</cfoutput>

but this throws the error "Object Instantiation Exception"

+1  A: 

Have you considered using SocketGateway?

http://help.adobe.com/en%5FUS/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-77f7.html

Henry
+1  A: 

For what it's worth, the code above worked perfectly when I tried it. I am on CF8.0.1. Thanks for the code.

Alex