我是scala世界的新手,所以请原谅我的琐碎问题。:) 我只想打开一个到端口的套接字并沙子并接收消息。如果我收到 HELO,我想对消息做出反应,但我无法以任何方式写入套接字。我使用 nc 来监听传入的连接:
nc -k -l 127.0.0.1 3333
当客户端连接我写
HELO
在 netcat 中,但客户端没有发送任何答案。
这是我的斯卡拉代码:
package hello
import java.io._
import java.net.{ InetAddress, ServerSocket, Socket, SocketException }
import java.util.Random
import scala.actors.Actor
import scala.actors.Actor._
object HelloWorld extends {
def main(args: Array[String]) {}
val ia = InetAddress.getByName("localhost");
val socket = new Socket(ia, 3333)
val out = new ObjectOutputStream(
new DataOutputStream(this.socket.getOutputStream))
val in = new DataInputStream(socket.getInputStream())
println("Starting client");
var i = 0;
/* The actor!
*
*/
val myActor = actor {
loop {
receive {
case s: String => {
if (s.startsWith("HELO")) {
println("DEBUG: RECEIVED HELO=>SENDING AUTH!")
this.out.writeUTF("HALLO")
this.out.flush();
} else {
println("received:" + s);
}
}
case _ => println("I have no idea what I just got.")
}
}
}
/*
* Testing the actor!
*
*/
myActor ! "foobar";
while (!socket.isConnected()) {
println("Not connected waiting")
Thread.sleep(5000);
}
if (socket.isConnected()) {
println("connected");
}
try {
while (true) {
i += 1;
val x = in.readLine()
myActor ! x;
Thread.sleep(500);
}
} catch {
case e: IOException =>
e.printStackTrace()
}
}
接收工作正常,演员对传入的消息做出反应,但写入从未完成。我只是在监督某些事情,还是我的代码错误地发送到 outputSteam。
这是我从控制台窗口的输出:
Starting client
connected
received:foobar
DEBUG: RECEIVED HELO=>SENDING AUTH!