老师,下面代码中注释掉的代码(蓝色)是起什么作用的?谢谢!
Public server As MyServer
Public Class MyServer
Private server As String
Private port As Integer
Private Const maxPacket As Integer = 64 * 1024
Public tcpl As System.Net.Sockets.TcpListener = Nothing
Public user_tb As New System.Collections.Hashtable() '客户端列表
Public msg As String '客户端登录信息
Public Sub New(ByVal ip As String, ByVal p As Integer)
server = ip
port = p
Dim clientThread As New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf newThread))
' clientThread.IsBackground = True
clientThread.Start(Nothing)
End Sub
Public Sub newThread(ByVal obj As Object)
Dim ip As System.Net.IPAddress = System.Net.IPAddress.Parse(server) '转换成IP
tcpl = New System.Net.Sockets.TcpListener(ip, port)
Try
tcpl.Start() '开始监听
Catch ex As Exception
MsgBox("端口" & port & "被占用,请改用其它端口")
Return
End Try
'开始侦听传入的连接请求.
try
msg &= "服务器已启动,正在监听..." & vbCrLf
msg &= String.Format("服务器IP:{0}" & vbTab & "端口号:{1}" & vbCrLf, ip, port)
While True
Dim packetBuff As Byte() = New Byte(maxPacket) {}
Dim newClient As System.Net.Sockets.Socket = tcpl.AcceptSocket() '接受客户端请求
Dim rlen As Integer = newClient.Receive(packetBuff)
Dim data As String = Encoding.Unicode.GetString(packetBuff, 0, rlen) '将接受的远程SOCKET,将数据存入接受缓冲区
user_tb.Add(data, newClient) '将客户端标识添加进hash表
Dim svrlog As String = String.Format("[系统消息]新用户 {0} 在 {1} 已连接... 当前在线人数: {2}" & vbCrLf, data, DateTime.Now, user_tb.Count)
msg &= svrlog
Dim clientThread As New System.Threading.Thread(New System.Threading.ParameterizedThreadStart(AddressOf ThreadFunc))
clientThread.Start(data)
' clientThread.IsBackground = True
newClient.Send(Encoding.Unicode.GetBytes("OK"))
End While
catch ex As exception
'msgbox("监听关闭成功")
End try
End Sub
Private Sub ThreadFunc(ByVal obj As Object)
Dim clientSkt As System.Net.Sockets.Socket = user_tb(obj)
While True
Try
Dim cmdBuff(128) As Byte
Dim rlen As Integer = clientSkt.Receive(cmdBuff) '静候客户端关闭
Catch ex As exception
msgbox("有一个客户端被关闭了")
user_tb.Remove(obj)
msg &= String.Format("[系统消息]用户 {0} 的客户端在 {1} 关闭!当前在线人数:{2}" & vbCrLf, obj, DateTime.Now, user_tb.Count)
System.Threading.Thread.CurrentThread.Abort()
End Try
End While
End Sub
Public Sub RemoveClient(ByVal obj As Object)
Dim clientSkt As System.Net.Sockets.Socket = user_tb(obj)
clientSkt.Send(New Byte() {1, 1}) '让客户正常关闭
End Sub
End Class