16,549
社区成员
发帖
与我相关
我的任务
分享
Dim m_aryClients As New ArrayList
Dim mServer As Socket
Delegate Sub AddClientToList(ByVal strName As String)
Delegate Sub AddRecvToText(ByVal strName As String)
Delegate Sub DeletClientFromList(ByVal strName As String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim addr As IPAddress = IPAddress.Parse("127.0.0.1")
For Each ipaddr As IPAddress In Dns.GetHostEntry(Dns.GetHostName()).AddressList
If ipaddr.ToString.StartsWith("192") Then
addr = ipaddr
Exit For
End If
Next
mServer = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '使用指定的地址族、套接字类型和协议初始化 Socket 类的新实例。
mServer.Bind(New IPEndPoint(addr, Int32.Parse(TextBox1.Text))) '使 System.Net.Sockets.Socket 与一个本地终结点相关联
mServer.Listen(100) '将 System.Net.Sockets.Socket 置于侦听状态
mServer.BeginAccept(AddressOf OnAccepted, mServer) '开始一个异步操作来接受一个传入的连接尝试
'Public Function BeginAccept(ByVal callback As System.AsyncCallback, ByVal state As Object) As System.IAsyncResult
End Sub
Protected Overridable Sub OnAccepted(ByVal ar As IAsyncResult) 'IAsyncResult(表示异步操作的状态)
Dim listener As Socket = CType(ar.AsyncState, Socket)
' End the operation.
Dim handler As Socket = listener.EndAccept(ar)
m_aryClients.Add(handler)
AddClientToListBox(handler.RemoteEndPoint.ToString()) 'RemoteEndPoint(获取远程终结点)
Dim state As New StateObject
state.workSocket = handler
mServer.BeginAccept(AddressOf OnAccepted, mServer)
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state) '开始从连接的 System.Net.Sockets.Socket 中异步接收数据
End Sub
Protected Overridable Sub ReadCallback(ByVal ar As IAsyncResult)
Dim content As String = String.Empty
Dim state As StateObject = CType(ar.AsyncState, StateObject)
Dim handler As Socket = state.workSocket
Dim bytesRead As Integer = 0
Try
bytesRead = handler.EndReceive(ar)
Catch ex As Exception
ToolStripStatusLabel1.Text = "客户端:" & handler.RemoteEndPoint.ToString & "强制关闭了!"
End Try
If bytesRead = 0 Then
DeleteClientFromListBox(handler.RemoteEndPoint.ToString())
m_aryClients.Remove(handler)
handler.Close()
Return
End If
AddRecvToTextBox(Encoding.ASCII.GetString(state.buffer))
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, New AsyncCallback(AddressOf ReadCallback), state)
End Sub 'ReadCallback
Dim barrSend As Byte() = Encoding.ASCII.GetBytes(TextBox3.Text)
For Each clientSend As Socket In m_aryClients
clientSend.Send(barrSend)
Next clientSend