3

我是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!
4

2 回答 2

2

If this code is truly the code you are using, it has a serious problem: it is using threads from inside a static initializer.

Here:

object HelloWorld extends {

Extends what?

def main(args: Array[String]) {}

No main method, so everything else is inside the constructor to object HelloWorld. Basically, that means everything using threads (including actors) is unreliable. Put this stuff inside the main method.

于 2010-08-12T21:45:38.343 回答
1

I'm not familiar with netcat, but is it possible that it's just not printing the "HALLO" response because it's encoded in a way that netcat can't make sense of (i.e. Java's serialization format)? Does it work if you don't wrap the output stream in an ObjectOutputStream?

于 2010-08-12T20:55:12.097 回答