Search code examples
socketshaskelltcp

How to send and receive messages from socket in Haskell


I am trying to create a TCP server in Haskell and so far i am not able to open a connection from a google browser extension and keep it open:

Error

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

Code

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

I have tried first only with sending messages and i get the up error, if i uncomment the lines with recv it hangs

Output with commented lines

"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)

Output with uncommented lines

"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"

P.S I am using Simple WebSocket Client-extension on Chrome and in both cases the connection appears "Opening" and not "Opened" even though the program runs a couple of iterations as you can see in the output(s)


Solution

  • The server worked just fine.The problem was that i was trying to connect using Chrome Simple WebSocket Client extension , which as the name says , tries to open a WebSocket connection , while my server handles simple Socket ones.

    I tried connecting to the server using telnet and it worked just fine (both sending and receiveing).