Socket programming in Clojure

人盡茶涼 提交于 2020-01-23 02:52:26

问题


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:


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




回答2:


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)


来源:https://stackoverflow.com/questions/25284724/socket-programming-in-clojure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!