3

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)
1
  • I have edited it to make it more idiomatic Clojure Commented Aug 13, 2014 at 16:32

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Thank you very much. There were a few other small errors which have been fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.