Question Working with socket

unibroue

New member
Joined
Aug 19, 2009
Messages
4
Programming Experience
1-3
Hi guys,

i have the following code :

VB.NET:
Const portNumber As Integer = 48888
        Dim writer = New System.IO.StreamWriter("c:\mylog.txt")
        writer.WriteLine(Date.Now + " Listening on port " + portNumber.ToString)
        ' Must listen on correct port- must be same as port client wants to connect on.
        tcpListener = New TcpListener(System.Net.IPAddress.Any, portNumber)
        tcpListener.Start()
        Do
            Try
                Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
                Dim networkStream As NetworkStream = tcpClient.GetStream()
                Dim bytes(tcpClient.ReceiveBufferSize) As Byte
                networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
                Dim clientdata As String = Encoding.ASCII.GetString(bytes)
                writer.WriteLine(Date.Now + " Creating folder " + clientdata)
                Dim responseString As String = "Connected to server."
                Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
                networkStream.Write(sendBytes, 0, sendBytes.Length)
                'Any communication with the remote client using the TcpClient can go here.
                'Close TcpListener and TcpClient.
                tcpClient.Close()
            Catch e As Exception
                writer.WriteLine(e.ToString)
            End Try
        Loop
        tcpListener.Stop()
        writer.Close()

The application is working good, i can receive data on port 48888 and i can write it to my logfile, but my problem is when i convert bytes to string. I have the correct data, but all the bufferReadSize is filled with space.

Example:

if i send only: test

my log file will have test and 4 lines of space only. In my code, right after

VB.NET:
Dim clientdata As String = Encoding.ASCII.GetString(bytes)

I tried to trim(), replaceI() or any string manipulation, and it's not working!%!? Is there anything i need to do before i can start manipulating that string?

thanks
 
Note: I get this error only when the app is running as a service! If i port this to a console app, it's working fine!

Note2: The problem seems to be with the do...loop! When i remove this, it's working. So how can i run a listening service without a loop or how to fix my current so it don't crash?
 
Back
Top