James T James T - 1 year ago 85
C# Question

C#.net XMLSocket app

I'm trying to make a C#.net app connect to a server using the XMLSocket protocal, I can do it with the following VB.net code but i'm not sure how to do it in C# as i'm just now learning it.

Public Sub connect(ByVal host As String, ByVal port As Integer)
mobjClient = New TcpClient(host, port)
mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
DisplayText("Connected to " & host & " On port " & port)
MarkAsDisconnected("Connection error.")
End Try
End Sub

Public Sub Send(ByVal t As String, Optional ByVal disp As Boolean = True)
Dim w As New IO.StreamWriter(mobjClient.GetStream)
w.Write(t & Chr(0))
If disp = True Then
End If
DisplayText("Error Sending!")
End Try
End Sub

Private Sub DoRead(ByVal ar As IAsyncResult)
Dim intCount As Integer
intCount = mobjClient.GetStream.EndRead(ar)
If intCount < 1 Then
'MarkAsDisconnected("Error reading Stream!")
DisplayText("Error reading stream.")
'Exit Sub
End If

BuildString(marData, 0, intCount)

mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
Catch e As Exception
connect("example.com", 7777)
LogIn("lograinbows", "inthesky", "DRESSLOGCASINO")
End Try
End Sub

''// This is important! Keep the Decoder and reuse it when you read this socket.
''// If you don't, a char split across two reads will break.
Dim decoder As Decoder = Encoding.UTF8.GetDecoder()

Private Sub BuildString(ByVal bytes() As Byte, ByVal offset As Integer, ByVal byteCount As Integer)
''// Here's where the magic happens. The decoder converts bytes into chars.
''// But it remembers the final byte(s), and doesn't convert them,
''// until they form a complete char.
Dim chars(bytes.Length) As Char
Dim charCount As Integer = decoder.GetChars(bytes, offset, byteCount, chars, 0)

For i As Integer = 0 To charCount - 1
If chars(i) = Chr(0) Then ''// The fix for bullet #2

Dim params() As Object = {mobjText.ToString}
Me.Invoke(New DisplayInvoker(AddressOf Me.HandleXML), params)

''// You don't have to make a new StringBuilder, BTW -- just clear it.
mobjText.Length = 0
End If
Catch e As Exception
DisplayText("Error: ", e.Message)
End Try
End Sub

Answer Source

All of your code can be trivially converted to C#.

If you need help, you can try an automated converter like this one or ask a more specific question.


  • The C# equivalent of Chr(0) is '\0'.
  • params is a C# keyword; you'll need to rename that variable.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download