James T James T - 1 month ago 13
Vb.net Question

VB.net flash XMLSocket substitution app

I'm trying to get a VB.net (express 2010) app to connect to a socket server (keeping the connection open), how would I go about this? Right now it works using flash XMLsocket, I'm trying to build a new client without flash, using the existing server.

Currently I'm just using a simple window displaying messages, and a place to send messages.

It says I'm connected, but it displays no messages, and sent messages appear to have no effect, when I telnet to the server using the same IP and port, I can see messages coming in to me, so I know I can connect to the server. Here is my code:

Imports System.Text
Imports System.Net.Sockets


Public Class Form1
Inherits System.Windows.Forms.Form

Public Delegate Sub DisplayInvoker(ByVal t As String)

Private mobjClient As TcpClient
Private marData(1024) As Byte
Private mobjText As New StringBuilder()

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
mobjClient = New TcpClient("example.com", 7777)
DisplayText("Connected to host " & "example.com")

mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
End Sub

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
Send(txtSend.Text)
txtSend.Text = ""
End Sub

Private Sub Send(ByVal t As String)
Dim w As New IO.StreamWriter(mobjClient.GetStream)
w.Write(t & vbCr)
w.Flush()
DisplayText(vbNewLine & "Sent " & t)
End Sub

Private Sub DoRead(ByVal ar As IAsyncResult)
Dim intCount As Integer
Try
intCount = mobjClient.GetStream.EndRead(ar)
If intCount < 1 Then
MarkAsDisconnected()
Exit Sub
End If

BuildString(marData, 0, intCount)

mobjClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoRead, Nothing)
Catch e As Exception
MarkAsDisconnected()
End Try
End Sub

Private Sub BuildString(ByVal Bytes() As Byte, ByVal offset As Integer, ByVal count As Integer)
Dim intIndex As Integer

For intIndex = offset To offset + count - 1
If Bytes(intIndex) = 10 Then
mobjText.Append(vbLf)

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

mobjText = New StringBuilder()
Else
mobjText.Append(ChrW(Bytes(intIndex)))
End If
Next
End Sub

Private Sub MarkAsDisconnected()
txtSend.ReadOnly = True
btnSend.Enabled = False
DisplayText(vbNewLine & "Dissconnected")
End Sub

Private Sub DisplayText(ByVal t As String)
txtDisplay.AppendText(t)
End Sub
End Class

Answer

As long as both apps speak TCP/IP, one has a listening server socket, and the other knows the IP and port number of that server socket and isn't blocked from connecting to it, it doesn't matter what language either app is written in. The point of having a protocol like TCP/IP is that it's effectively independent of platform, OS, framework, language, or much of anything else.

As for your code, a few things stand out:

  • You're creating a new StreamWriter attached to the network stream every time you send anything. If the writer closes and disposes itself on finalization, which most IDisposables do, it would close the underlying stream (which, in the case of the TcpClient's stream, will close the connection). If you're going to use a writer to send data, keep one as an instance variable and reuse it rather than creating a new one each time.

  • From reading about the XmlSocket protocol, it seems the strings sent and received should be null-terminated. That is, your loop inside BuildString should be looking for 0 rather than 10 when breaking up the data into strings, and Send should be appending a nul character (Chr(0)) rather than a vbCr to every string it sends.

  • You really should be using an encoding to convert bytes to chars. Your existing code (when fixed as above) should at least show you some data, assuming there's any to be sent. You may well find the data corrupted, though, due to the assumption that 1 byte == 1 char -- which is rarely the case since Unicode hit it big. :) I'd suggest you use a StreamReader rather than reading directly from the stream -- the StreamReader uses an Encoding behind the scenes (the UTF-8 one by default, IIRC), and will handle most of the gory details, so you don't need to worry about how many bytes to read to get a char. But StreamReaders don't have the stuff built into them to do async reads. You'd have to change your stuff a bit, and spawn a thread for it, in order to use a StreamReader.

You could use a Decoder directly, which is pretty much what a StreamReader does. Use it something like this:

''// 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.
Private _decoder As Decoder = UTF8Encoding.GetDecoder()


Private Sub BuildString(bytes() As Byte, offset As Integer, 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
            mObjText.Append(vbLf)

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

            ''// You don't have to make a new StringBuilder, BTW -- just clear it.
            mObjText.Length = 0
        else
            mObjText.Append(chars(i))
        end if
    Next
End Sub

(BTW, the comments are started funny so that the syntax highlighting acts less stupid.)