asked on
Option Compare Database
Option Explicit
Public Const COMMAND_ERROR = -1
Public Const RECV_ERROR = -1
Public Const NO_ERROR = 0
Public socketId As Long
'Global Variables for WINSOCK
Global State As Integer
Sub CloseConnection()
Dim x As Long
' we close our connection here
x = closesocket(socketId)
If x = SOCKET_ERROR Then
MsgBox ("ERROR: closesocket = " + Str$(x))
Exit Sub
End If
End Sub
Sub EndIt()
Dim x As Long
'Shutdown Winsock DLL
x = WSACleanup()
End Sub
Function OpenSocket(ByVal Hostname As String, ByVal PortNumber As Integer) As Integer
Dim I_SocketAddress As sockaddr_in
Dim ipAddress As Long
Dim x As Long
ipAddress = inet_addr(Hostname)
'Create a new socket
socketId = socket(AF_INET, SOCK_STREAM, 0)
If socketId = SOCKET_ERROR Then
MsgBox ("ERROR: socket = " + Str$(socketId))
OpenSocket = COMMAND_ERROR
Exit Function
End If
'Open a connection to a server
I_SocketAddress.sin_family = AF_INET
I_SocketAddress.sin_port = htons(PortNumber)
I_SocketAddress.sin_addr = ipAddress
I_SocketAddress.sin_zero = String$(8, 0)
x = connect(socketId, I_SocketAddress, Len(I_SocketAddress))
If socketId = SOCKET_ERROR Then
MsgBox ("ERROR: connect = " + Str$(x))
OpenSocket = COMMAND_ERROR
Exit Function
End If
OpenSocket = socketId
End Function
Function SendCommand(ByVal command As String) As Integer
' our communication command...
Dim strSend As String
Dim count As Long
strSend = command + vbCrLf
count = send(socketId, ByVal strSend, Len(strSend), 0)
If count = SOCKET_ERROR Then
MsgBox ("ERROR: send = " + Str$(count))
SendCommand = COMMAND_ERROR
Exit Function
End If
SendCommand = NO_ERROR
End Function
Function RecvAscii(dataBuf As String, ByVal maxLength As Integer) As Integer
On Error GoTo Error_Handler
DoEvents
Dim c As String * 12288
Dim length As Integer
dataBuf = ""
DoEvents
dataBuf = recv(socketId, c, 12288, 0)
dataBuf = c
length = Len(dataBuf)
Exit Function
Error_Handler:
DoEvents
MsgBox Err.Number & " " & Err.Description
DoEvents
End Function
Function StartIt()
Dim StartUpInfo As WSAData
Dim Version As Integer
Dim x As Long
'Version 1.1 (1*256 + 1) = 257
'version 2.0 (2*256 + 0) = 512
'Get WinSock version
Version = (1 * 256 + 1)
'Initialize Winsock DLL
x = WSAStartup(Version, StartUpInfo)
End Function