Example of a chat room in an SDK (2)

Source: Internet
Author: User
Tags flush goto integer socket socket error
Chat room

' Nested Enum for supported states
Public Enum Status
Listening
Connected
End Enum ' Status


' Start up ' 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 (the 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'll generate a exception when
' The remote connection closes. We handle this case into 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'll generate a notification.end
' Here's 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 are 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 a 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 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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.