我写了这个简单的tcp服务器:
import Network
import Network.Socket.ByteString
main :: IO()
main = do
sock <- listenOn $ PortNumber 2000
contents <- recv sock 4096
print contents
堆栈构建成功,然后我运行服务器,使用telnet测试它,但我收到一个错误:
在linux上:
Network.Socket.recvBuf:invalid argument (Transport endpoint is not connected)
在Windows上:
Network.Socket.recvBuf:failed(No error)
该计划有什么问题?
答案 0 :(得分:5)
listenOn
只是创建一个“侦听套接字”,它“监听”与服务器的新连接。您应该使用accept
函数来获取新客户端,如下所示:
main :: IO ()
main = do
sock <- listenOn $ PortNumber 2000
(client, _, _) <- accept sock
contents <- hGetContents client
print contents
sClose sock
或者使用低级accept
函数(来自Network.Socket
模块)来获取套接字:
main :: IO ()
main = do
sock <- listenOn $ PortNumber 2000
(client, _) <- accept sock
contents <- recv client 4096
print contents
sClose client
sClose sock
如果您想处理更多客户,可以使用forkIO
,如下所示:
main :: IO ()
main = do
sock <- listenOn $ PortNumber 2000
forever $ do
(client, _) <- accept sock
forkIO $ do
contents <- recv client 4096
print contents
sClose client