【VB开源代码栏目提醒】:网学会员VB开源代码为您提供frmServerM.frm参考,解决您在frmServerM.frm学习中工作中的难题,参考学习。
VERSION 5.00
Object = "{248DD890-BB45-11CF-9ABC-0080C7E7B78D}#1.0#0"; "MSWINSCK.OCX"
Begin VB.Form frmServerM
Caption = "TCP服务器"
ClientHeight = 4005
ClientLeft = 60
ClientTop = 450
ClientWidth = 4845
LinkTopic = "Form1"
ScaleHeight = 4005
ScaleWidth = 4845
StartUpPosition = 3 '窗口缺省
Begin VB.CommandButton cmdShowClient
Caption = "显示多个客户端"
Height = 375
Left = 2640
TabIndex = 5
Top = 3480
Width = 1575
End
Begin VB.TextBox txtAccept
Height = 2055
Left = 240
MultiLine = -1 'True
ScrollBars = 3 'Both
TabIndex = 3
Top = 1200
Width = 4335
End
Begin VB.CommandButton cmdSend
Caption = "发送"
Height = 375
Left = 1200
TabIndex = 1
Top = 3480
Width = 1095
End
Begin MSWinsockLib.Winsock wskServer
Index = 0
Left = 240
Top = 3480
_ExtentX = 741
_ExtentY = 741
_Version = 393216
End
Begin VB.TextBox txtSendData
Height = 375
Left = 1320
TabIndex = 0
Top = 240
Width = 3255
End
Begin
VB.Label Label2
Caption = "接收的信息:"
Height = 255
Left = 240
TabIndex = 4
Top = 840
Width = 1215
End
Begin VB.Label Label1
Caption = "发送的信息:"
Height = 255
Left = 240
TabIndex = 2
Top = 360
Width = 1095
End
End
Attribute VB_Name = "frmServerM"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Dim ClientNum As Integer
Dim n As Integer
Private Sub Form_Load()
ClientNum = 0
wskServer(0).LocalPort = 1002
'
程序启动时侦听
wskServer(0).Listen
End Sub
Private Sub cmdSend_Click()
For i = 1 To ClientNum '循环向所有客户端发送信息
If Not wskServer(i) Is Nothing Then '首先判断Winsock控件是否还存在
DoEvents
wskServer(i).SendData "服务器:" & txtSendData.Text '发送信息到客户端
End If
Next
End Sub
Private Sub cmdShowClient_Click()
n = n + 1
Dim frmc As New frmClientM
frmc.Caption = "TCP客户端" & CStr(n)
frmc.Show
End Sub
Private Sub wskServer_ConnectionRequest(Index As Integer, ByVal requestID As Long)
If Index = 0 Then
ClientNum = ClientNum + 1 '将客户端连接数增加1
Load wskServer(ClientNum) '载入一个新的Winsock控件,通过Load命令
wskServer(ClientNum).LocalPort = 1002
wskServer(ClientNum).Accept requestID '新载入的Winsock控件接受客户端的请求
wskServer(ClientNum).SendData "欢迎光临!!" '向新来的客户端发送信息
End If
End Sub
Private Sub wskServer_DataArrival(Index As Integer, ByVal bytesTotal As Long)
'不同Index参数对应不同的Winsock控件,可以区分来自哪个客户端
Dim myData As String
wskServer(Index).GetData myData '将数据保存在变量myData 中
txtAccept.Text = txtAccept.Text + myData + vbCrLf '在文本框中显示信息
End Sub
Private Sub wskServer_Error(Index As Integer, _
ByVal Number As Integer, Description As String, _
ByVal Scode As Long, ByVal Source As String, _
ByVal HelpFile As String, ByVal HelpContext As Long, CancelDisplay As Boolean)
wskServer(Index).Close '关闭客户端连接
End Sub
Private Sub wskServer_Close(Index As Integer)
wskServer(Index).Close '关闭客户端连接
End Sub