Reputation: 35
I'm a Clojure noob, so bear with me. I'm trying to write a simple program to send a command through a socket and get a response. My code is:
(def IPaddress "10.71.18.81")
(def port 1500)
(def socket (new Socket IPaddress port))
(print (clojure.string/join ["\nConnected to HSM: " (. socket isConnected)]))
(def in (DataInputStream. (BufferedInputStream. (. socket getInputStream))))
(def out (DataOutputStream. (BufferedOutputStream. (. socket getOutputStream))))
(def command "Some string")
(. out WriteUTF command)
(def response (. in readUTF))
(print (clojure.string/join ["Output from HSM: " response]))
The error is "Exception in thread "main" java.lang.IllegalArgumentException: No matching method: writeUTF". I'm having trouble understanding Java interop, and accessing object methods, etc. Thanks in advance.
EDIT: If anyone is interested, my final working code is included here:
(def IPaddress "10.71.18.81")
(def port 1500)
(def socket (Socket. IPaddress port))
(println "Connected:" (.isConnected socket))
(def in (DataInputStream. (BufferedInputStream. (.getInputStream socket))))
(def out (DataOutputStream. (BufferedOutputStream. (.getOutputStream socket))))
(def command "Some string")
(println "Input:" command)
(.writeUTF out command)
(.flush out)
(def response (.readUTF in))
(println "Output: " response)
Upvotes: 3
Views: 3813
Reputation: 29
I realize this is pretty old but it is one of the only examples I have found for reading and writing to a socket with clojure. I needed to experiment a bit to get your code working so it might be useful to someone to the results of that effort:
(import (java.net Socket))
(import (java.io DataInputStream DataOutputStream))
(def IPaddress "127.0.0.1")
(def port 1500)
(def command "Some string\n")
(def socket (Socket. IPaddress port))
(def in (DataInputStream. (.getInputStream socket)))
(def out (DataOutputStream. (.getOutputStream socket)))
(println "Input:" command)
(.writeUTF out command)
(def response (.readLine in))
(println "Output: " response)
Upvotes: 3
Reputation: 8593
Java is case sensite so it should be (. out writeUTF command)
. Note that the prefer syntax for interop is (.writeUTF out command)
which is equivalent to your statement
Upvotes: 2