如何从Haskell中的套接字发送和接收消息

时间:2019-04-16 12:57:24

标签: sockets haskell tcp

我正在尝试在Haskell中创建TCP服务器,但到目前为止,我无法通过Google浏览器扩展程序打开连接并保持打开状态:

错误

Server.exe: Network.Socket.sendBuf: failed (Unknown error)

代码

import Network.Socket
import qualified Network.Socket.ByteString as B
import Data.ByteString.Char8(pack,unpack)

main::IO()
main=do
    sock<-socket AF_INET Stream 0
    bind sock (SockAddrInet 8500 iNADDR_ANY)
    listen sock 3
    (csock,_)<-accept sock
    loop csock

loop::Socket->IO()
loop csock=do
    print "Begining of loop"
   -- dat<-B.recv csock 2000
    sent<-B.send  csock $ pack "Hi!!"
  --  print $ unwords  ["Received :",unpack dat]
    print "End of loop"
    loop csock

我只尝试过发送消息,但是如果我用recv取消注释行,它就会挂起

带有注释行的输出

"Begining of loop"
"End of loop"
"Begining of loop"
"End of loop"
"Begining of loop"
"End of loop"
"Begining of loop"
Server.exe: Network.Socket.sendBuf: failed (Unknown error)

带有未注释行的输出

"Begining of loop"
"Received : GET / HTTP/1.1\r\nHost: localhost:8500\r\nConnection: Upgrade\r\nPragma: no-cache\r\nCache-Control: no-cache\r\nUpgrade: websocket\r\nOrigin: chrome-extension://pfdhoblngboilpfeibdedpjgfnlcodoo\r\nSec-WebSocket-Version: 13\r\nUser-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/73.0.3683.103 Safari/537.36\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: en,en-US;q=0.9,ro;q=0.8\r\nSec-WebSocket-Key: WY87jPXNRfk/WM5T20O8Jg==\r\nSec-WebSocket-Extensions: permessage-deflate; client_max_window_bits\r\n\r\n"
"End of loop"
"Begining of loop"

PS 我在Chrome上使用Simple WebSocket Client扩展名,在两种情况下,连接都显示为“正在打开”而不是“已打开”,即使程序运行了几次迭代(如您在输出中所见)

1 个答案:

答案 0 :(得分:0)

服务器工作正常。问题是我试图使用Chrome Simple WebSocket Client扩展名进行连接,顾名思义,该扩展名试图打开WebSocket连接,而我的服务器处理简单的{{ 1}}个。

我尝试使用Socket连接到服务器,并且工作正常(发送和接收)。