gpt4 book ai didi

sockets - 向套接字发送(或接收)数据时出错(Haskell)

转载 作者:行者123 更新时间:2023-12-03 11:57:26 25 4
gpt4 key购买 nike

我在弄乱我在网上找到的回显服务器,试图用Haskell进行网络编程,但我遇到了一个绊脚石。我似乎无法弄清楚如何(通过另一个程序或任何其他方式)将数据发送到服务器。我目前的尝试如下:

import Network (connectTo, Socket, PortID(..))
import System.IO (hPutStrLn, hClose, hSetBuffering, BufferMode(..))

main :: IO ()
main = do
handle <- connectTo "127.0.0.1" (PortNumber 5555)
hSetBuffering handle LineBuffering
hPutStrLn handle "echo hello, world!"
hPutStrLn handle "add 1 2"
hClose handle

当我运行main时,在运行服务器的终端中出现错误“Server.hs::hPutChar:资源消失(管道损坏)”。服务器代码如下:
import Network   (listenOn, accept, withSocketsDo, PortID(..), Socket)
import System (getArgs)
import System.IO (hSetBuffering, hGetLine, hPutStrLn, BufferMode(..), Handle)
import Control.Concurrent (forkIO)

main :: IO ()
main = withSocketsDo $ do
args <- getArgs
let port = fromIntegral (read $ head args :: Int)
sock <- listenOn $ PortNumber port
putStrLn $ "Listening on " ++ show port
sockHandler sock

sockHandler :: Socket -> IO ()
sockHandler sock = do
(handle, _, _) <- accept sock
hSetBuffering handle NoBuffering
forkIO $ commandProcessor handle
sockHandler sock

commandProcessor :: Handle -> IO ()
commandProcessor handle = do
line <- hGetLine handle
let cmd = words line
case (head cmd) of
("echo") -> echoCommand handle cmd
("add") -> addCommand handle cmd
_ -> do hPutStrLn handle "Unknown command."
commandProcessor handle

echoCommand :: Handle -> [String] -> IO ()
echoCommand handle cmd = do
hPutStrLn handle (unwords $ tail cmd)

addCommand :: Handle -> [String] -> IO ()
addCommand handle cmd = do
hPutStrLn handle $ show $ (read $ cmd !! 1) + (read $ cmd !! 2)

我该如何解决这个问题?我想扩展服务器,以便我可以学习更多。谢谢!

最佳答案

在这种情况下,问题很简单。您正在向服务器写入回显命令,然后是添加命令,然后断开连接。然后,服务器尝试处理echo命令,然后尝试写回客户端,但是客户端已经断开连接!因此,您将获得一个异常(exception)。

客户端无法断开连接,直到它从服务器读回足够的数据为止-服务器应该处理异常,以便客户端断开连接不会杀死它。

关于sockets - 向套接字发送(或接收)数据时出错(Haskell),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5600712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com