聊天室
' Nested enum for supported states
Public Enum Status
Listening
Connected
End Enum 'Status
' Start up the talker's functionality
Public Sub Start()
ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf EstablishSocket))
End Sub 'Start
' Establish a socket connection and start receiving
Private Sub EstablishSocket(ByVal state As Object)
Try
' If not client, setup listner
If Not client Then
Dim listener As Socket
Try
listener = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
listener.Blocking = True
listener.Bind(endPoint)
SetStatus(Status.Listening)
listener.Listen(0)
socket = listener.Accept()
listener.Close()
Catch e As SocketException
' If there is already a listener on this port try client
If e.ErrorCode = 10048 Then
client = True
endPoint = New IPEndPoint(Dns.Resolve("127.0.0.1").AddressList(0), endPoint.Port)
Else
RaiseEvent Notifications(Notification.ErrorNotify, "Error Initializing Socket:" & ControlChars.CrLf & e.ToString())
End If
End Try
End If
' Try a client connection
If client Then
Dim temp As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
temp.Blocking = True
temp.Connect(endPoint)
socket = temp
End If
' If it all worked out, create stream objects
If Not (socket Is Nothing) Then
SetStatus(Status.Connected)
Dim stream As New NetworkStream(socket)
reader = New StreamReader(stream)
writer = New StreamWriter(stream)
RaiseEvent Notifications(Notification.Initialized, Me)
Else
RaiseEvent Notifications(Notification.ErrorNotify, "Failed to Establish Socket")
End If
' Start receiving talk
' Note: on w2k and later platforms, the NetworkStream.Read()
' method called in ReceiveTalke will generate an exception when
' the remote connection closes. We handle this case in our
' catch block below.
ReceiveTalk()
' On Win9x platforms, NetworkStream.Read() returns 0 when
' the remote connection closes, prompting a graceful return
' from ReceiveTalk() above. We will generate a Notification.End
' message here to handle the case and shut down the remaining
' WinTalk instance.
RaiseEvent Notifications(Notification.EndNotify, "Remote connection has closed.")
Catch e As IOException
Dim sockExcept As SocketException = CType(e.InnerException, SocketException)
If Not (sockExcept Is Nothing) And 10054 = sockExcept.ErrorCode Then
RaiseEvent Notifications(Notification.EndNotify, "Remote connection has closed.")
Else
RaiseEvent Notifications(Notification.ErrorNotify, "Socket Error:" & ControlChars.CrLf & e.Message)
End If
Catch e As Exception
RaiseEvent Notifications(Notification.ErrorNotify, "Socket Error:" & ControlChars.CrLf & e.Message)
End Try
End Sub 'EstablishSocket
' Send text to remote connection
Public Sub SendTalk(ByVal newText As String)
Dim send As String
' Is this an append
If prevSendText.Length <= newText.Length And String.CompareOrdinal(newText, 0, prevSendText, 0, prevSendText.Length) = 0 Then
Dim append As [String] = newText.Substring(prevSendText.Length)
send = String.Format("A{0}:{1}", append.Length, append)
' or a complete replacement
Else
send = String.Format("R{0}:{1}", newText.Length, newText)
End If
' Send the data and flush it out
writer.Write(send)
writer.Flush()
' Save the text for future comparison
prevSendText = newText
End Sub 'SendTalk
' Send a status notification
Private Sub SetStatus(ByVal statusObj As Status)
Me.statusObj = statusObj
RaiseEvent Notifications(Notification.StatusChange, statusObj)
End Sub 'SetStatus
' Receive chat from remote client
Private Sub ReceiveTalk()
Dim commandBuffer(19) As Char
Dim oneBuffer(0) As Char
Dim readMode As Integer = 1
Dim counter As Integer = 0
Dim textObj As New StringBuilder()
While readMode <> 0
If reader.Read(oneBuffer, 0, 1) = 0 Then
readMode = 0
Goto ContinueWhile1
End If
Select Case readMode
Case 1
If counter = commandBuffer.Length Then
readMode = 0
Goto ContinueWhile1
End If
If oneBuffer(0) <> ":"c Then
commandBuffer(counter) = oneBuffer(0)
counter = counter + 1
Else
counter = Convert.ToInt32(New String(commandBuffer, 1, counter - 1))
If counter > 0 Then
readMode = 2
textObj.Length = 0
Else
If commandBuffer(0) = "R"c Then
counter = 0
prevReceiveText = String.Empty
RaiseEvent Notifications(Notification.Received, prevReceiveText)
End If
End If
End If
Case 2
textObj.Append(oneBuffer(0))
counter = counter - 1
If counter = 0 Then
Select Case commandBuffer(0)
Case "R"c
prevReceiveText = textObj.ToString()
Case Else
prevReceiveText += textObj.ToString()
End Select
readMode = 1
RaiseEvent Notifications(Notification.Received, prevReceiveText)
End If
Case Else
readMode = 0
Goto ContinueWhile1
End Select
ContinueWhile1:
End While
End Sub 'ReceiveTalk
Private socket As socket
Private reader As TextReader
Private writer As TextWriter
Private client As Boolean
Private endPoint As IPEndPoint
Private prevSendText As String
Private prevReceiveText As String
Private statusText As String
Private statusObj As Status
End Class 'Talker
一个SDK里做聊天室的例子(2)
80酷酷网 80kuku.com