2011年3月3日 星期四

如何運用WinSock 來傳送資料

'傳送端
'此處需要1個WinSock,1個Timer,3個Button
Option Explicit
Dim blnConnect As Boolean

Private Sub cmdConnect_Click() '連線
On Error Resume Next
With Winsock1
If .State = sckConnected Then Exit Sub
If .State <> sckClosed Then .Close
.Protocol = sckTCPProtocol
.Connect txtRemoteIP, txtPort
End With
blnConnect = False
Timer1.Interval = txtSec * 1000
End Sub

Private Sub cmdExit_Click()
Unload Me
End Sub

Private Sub cmdSend_Click() '傳送資料
On Error Resume Next
Winsock1.SendData txtReceivedData
End Sub

Private Sub Timer1_Timer() '
On Error Resume Next
If Not blnConnect Then MsgBox "連線逾時(" & txtSec & ")!!"
Timer1.Interval = 0
End Sub

Private Sub Winsock1_Connect()
blnConnect = True
MsgBox "連線OK"
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long) '接收資料
Dim xx As String
Winsock1.GetData xx, vbString
txtReceivedData = txtReceivedData & CStr(xx)

End Sub

'接收端
'此範例是用物件陣列開2個Port 來傳送/接收資料
'此處需要2個winsock,4個Button,4個TextBox
Option Explicit

Private Sub cmdConnect_Click(Index As Integer) '連線
With Winsock1(Index)
.Bind txtPort(Index), .LocalIP
.Listen
End With

End Sub

Private Sub cmdExit_Click() '結束
Unload Me
End Sub

Private Sub cmdSend_Click() '傳送資料
On Error Resume Next
Dim intLoop As Integer
For intLoop = 0 To 1
Winsock1(intLoop).SendData txtReceivedData(intLoop)
Next
End Sub

Private Sub Timer1_Timer()
Dim intLoop As Integer
For intLoop = 0 To Winsock1.UBound
If Winsock1(intLoop).State <> sckClosed Then
lblReceivedData(intLoop).ForeColor = &H8000000F
Else
lblReceivedData(intLoop).ForeColor = &HFF&
End If
Next
End Sub

Private Sub Winsock1_ConnectionRequest(Index As Integer, ByVal requestID As Long)
If Winsock1(Index).State <> sckClosed Then Winsock1(Index).Close
Winsock1(Index).Accept requestID
End Sub

Private Sub Winsock1_DataArrival(Index As Integer, ByVal bytesTotal As Long) '接收資料
Dim xx As String
Winsock1(Index).GetData xx, vbString
txtReceivedData(Index) = txtReceivedData(Index) & CStr(xx)
End Sub

沒有留言:

張貼留言