为什么这个示例TCP Server在未关闭的情况下抛出异常?

时间:2011-06-01 21:27:01

标签: tcp groovy client

这是以

的方式用Groovy编写的

我有一段时间没有弄乱我的TCP服务器脚本并且决定我希望它保持打开并且即使在使用它之后仍然继续收听而不仅仅是一次使用。但是,当我这样做时,它会抛出异常然后关闭脚本。

我的示例脚本如下:

TCP服务器

def server = new ServerSocket(2000)

println("Waiting for connection")


    server.accept() { socket ->
        socket.withStreams { input, output ->

        w = new BufferedWriter(new OutputStreamWriter(output))
        String message = "Connection was successful"

            r = new BufferedReader(new InputStreamReader(input))

        while(true) {
        if(message !=null) {
            sendMessage(message)
            message = null
        }

        String a = r.readLine()

        if(a.equals("name"))
            message = "Bob"
        else if(a.equals("date"))
            message = new Date()
        else if(a.equals("ip")) 
            message = InetAddress.getLocalHost().getHostAddress()
        else if(a.equals("quit")) {
            server.close()
            return
        } else 
            message = "$a command unknown"
        }
        }
    }

def sendMessage(String msg) {
    println("Sending: >" + msg + "<")
    w.writeLine(msg)
    w.flush();
}

问题出在客户端。如果我使用quit命令,则在其他命令完成后关闭服务器。但是,如果我从命令中删除quit,则服务器会尝试保持打开状态,抛出异常,然后关闭服务器。

TCP客户端

def commands 
def answers
def requestSocket
def r
def w

String host = "filipekdt7"
commands = ["name",
        "date",
        "ip",
        "quit"]   //If I take out "quit" then the exceptions get thrown, but I want to leave my server script running

answers = [commands.size]

requestSocket = new Socket(host, 2000)

r = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()))
w = new BufferedWriter(new OutputStreamWriter(requestSocket.getOutputStream()))

String message = r.readLine()
println "Server >" + message

for(int n = 0; n < commands.size; n++) {
    sendMessage(commands[n],w)
    answers[n] = r.readLine()
}

w.flush()
w.close()


public String sendMessage(def msg, def w) {
    w.write(msg+"\r\n")
    w.flush()
    println "Client>" + msg
}

有谁知道保持服务器脚本运行的方法?我想我只是在寻找一些简单的东西。

1 个答案:

答案 0 :(得分:2)

尝试将服务器代码修改为:

def server = new ServerSocket(2000)
println("Waiting for connection")

while (true) {
    server.accept() { socket ->
        socket.withStreams { input, output ->
            def w = new BufferedWriter(new OutputStreamWriter(output))
            String message = "Connection was successful"
            def r = new BufferedReader(new InputStreamReader(input))

            while (true) {
                if (message !=null) {
                    sendMessage(message, w)
                    message = null
                }

                String a = r.readLine()
                if (a == null) {
                    socket.close()
                    println "Client disconnected"
                    return
                } else if (a.equals("name")) {
                    message = "Bob"
                } else if (a.equals("date")) {
                    message = new Date()
                } else if (a.equals("ip")) {
                    message = InetAddress.getLocalHost().getHostAddress()
                } else if (a.equals("quit")) {
                    server.close()
                    return
                } else { 
                    message = "$a command unknown"
                }
            }
        }
    }
}

def sendMessage(msg, writer) {
    println("Sending: >" + msg + "<")
    writer.writeLine(msg.toString())
    writer.flush();
}

注意ServerSocket循环中accept重复while个连接的方式。这使服务器脚本保持运行。

您之前收到异常是因为您尝试向已与服务器断开连接的客户端发送消息。要解决此问题,您应该在尝试发送响应之前验证从客户端读取的命令是否有效(即a != null)。