Skip to content

Request Response

Jiowcl edited this page Jun 18, 2021 · 1 revision

Request / Response

Server

#Include "../Core/ZeroMQ.bi"

Dim lpszLibZmqDll As String = "libzmq.dll"

Const lpszServerAddr As String = "tcp://*:1700"

Dim hLibrary As Any Ptr = ZmqDllOpen(lpszLibZmqDll)

If hLibrary > 0 Then
    Dim Context As Any Ptr = ZmqCtxNew(hLibrary)
    Dim Socket As Any Ptr = ZmqSocket(hLibrary, Context, ZMQ_REP)
    Dim Rc As Long = ZmqBind(hLibrary, Socket, lpszServerAddr)
    
    Print("Bind an IP address: " & lpszServerAddr)
    
    Dim lTotal As Integer = 0
    
    While 1
        lTotal = lTotal + 1
        
        Dim lpszRecvBufferPtr As Any Ptr = CAllocate(32)
        Dim lpszSendBufferPtr As ZString Ptr
        Dim lpszSendMessage As String = "Hi " & lTotal

        ZmqRecv(hLibrary, Socket, lpszRecvBufferPtr, 32, 0)
        
        Sleep(2)
        
        Print("Received: ")
        Print(*CPtr(Zstring Ptr, lpszRecvBufferPtr))
        
        lpszSendBufferPtr = CAllocate(Len(lpszSendMessage), SizeOfDefZStringPtr(lpszSendBufferPtr))
        *lpszSendBufferPtr = lpszSendMessage

        ZmqSend(hLibrary, Socket, lpszSendBufferPtr, Len(lpszSendMessage), 0)
        
        Deallocate(lpszRecvBufferPtr) 
        Deallocate(lpszSendBufferPtr) 

        lpszRecvBufferPtr = 0
        lpszSendBufferPtr = 0
    Wend
    
    ZmqClose(hLibrary, Socket)
    ZmqCtxShutdown(hLibrary, Context)
    
    ZmqDllClose(hLibrary)
End If

Client

#Include "../Core/ZeroMQ.bi"

Dim lpszLibZmqDll As String = "libzmq.dll"

Const lpszServerAddr As String = "tcp://localhost:1700"

Dim hLibrary As Any Ptr = ZmqDllOpen(lpszLibZmqDll)

If hLibrary > 0 Then
    Dim Context As Any Ptr = ZmqCtxNew(hLibrary)
    Dim Socket As Any Ptr = ZmqSocket(hLibrary, Context, ZMQ_REQ)
    Dim Rc As Long = ZmqConnect(hLibrary, Socket, lpszServerAddr)
    
    Print("Connect to Server: " & lpszServerAddr)
    
    Dim i As Integer
    
    For i = 0 To 10 
        Dim lpszSendBufferPtr As ZString Ptr
        Dim lpszRecvBufferPtr As Any Ptr = CAllocate(32)
        Dim lpszSendMessage As String = "From Client"

        lpszSendBufferPtr = CAllocate(Len(lpszSendMessage), SizeOfDefZStringPtr(lpszSendBufferPtr))
        *lpszSendBufferPtr = lpszSendMessage

        ZmqSend(hLibrary, Socket, lpszSendBufferPtr, Len(lpszSendMessage), 0)
        ZmqRecv(hLibrary, Socket, lpszRecvBufferPtr, 32, 0)
        
        Print("Reply From Server: ")
        Print(*CPtr(Zstring Ptr, lpszRecvBufferPtr))
        
        Deallocate(lpszSendBufferPtr)
        Deallocate(lpszRecvBufferPtr) 

        lpszSendBufferPtr = 0
        lpszRecvBufferPtr = 0
    Next 
    
    ZmqClose(hLibrary, Socket)
    ZmqCtxShutdown(hLibrary, Context)
    
    Input("")
    
    ZmqDllClose(hLibrary)
End If

Clone this wiki locally