我正在尝试编写一个简单的TCP客户端,它使用Java Socket
向远程主机发送请求。该应用程序是同步的,因此它将首先发送和接收,并将一直阻止,直到收到响应。
我能够与远程主机创建一个Socket连接,似乎我能够毫无问题地发送请求,但是我从未收到服务器的响应,因此它最终会挂起。
另外,看看Wireshark似乎并没有表明任何数据报发送到指定主机IP或从指定主机IP接收(我应该添加主机通过VPN访问,我已经验证我可以在命令行上ping )。听起来这可能是一个网络问题,但以防万一我认为值得进行健全性检查以确定代码是否存在问题:
(defn- receive
"Given a reader and a socket, create a DataInputStream and process the server
response"
[reader socket]
(let [byte-in (make-array Byte/TYPE b/max-message-size)]
(log/receive socket b/max-message-size)
(.read reader byte-in)
byte-in))
(defn- transmit
"Given a writer, a socket and a message, create a DataOutputStream
and send request to the server"
[writer socket message]
(let [byte-out (r/make-request socket message)]
(log/begin-transmit socket byte-out)
(.write writer byte-out)
(log/end-transmit writer)
(.flush writer)))
(defn send-request
"Given a message, create a Socket and process the request"
[msg]
(with-open [socket (java.net.Socket. (:host-ip msg) (:host-port msg))
writer (DataOutputStream. (.getOutputStream socket))
reader (DataInputStream. (.getInputStream socket))]
(println "Initializing TCP request ...\n")
(transmit writer socket msg)
(receive reader socket)))
以下是来自传输的输出 - 它在接收功能期间挂起。请注意,指示的主机IP和主机端口取自Socket
对象实例的字段:
Transmitting request
-------------------------------
Message Size : 123 bytes
Host IP : /192.168.xxx.xxx
Host Port : 2605
Bytes written: 123 bytes
Receiving response
--------------------------------
Maximum Size : 146 bytes
Host IP : /192.168.xxx.xxx
Host Port : 2605