Socket read line by line...

vinnie881

Well-known member
Joined
Sep 3, 2006
Messages
152
Programming Experience
3-5
I am using the socket class and using a traditional method of reading the socket by 1024 byte.

This causes an issue as the app I am writing needs to monitor this socket line by line in sequence live to properly work


So for instance I read from the socket


Event:caller
View state:6369

Event:hangup

Ev
...


The socket never closes, but my next read could be cutoff such as

ent:Answer
Viewstate:8846


As you can see above the ev got cut off due to the 1024 read.


I instead want to read the buffer in sequence stopping at the line feeds so my text can be fully evaluated. How would I do this?
 
Here is basically the code I'm using
Imports System.Net
Imports System.Net.Sockets
Imports System.Text.RegularExpressions
Imports System.Text

Namespace AsteriskPrototype
	Class AppConsole
		<STAThread> _
		Private Shared Sub Main(args As String())
			Console.WriteLine("Quick and Dirty Asterisk Manager Daemon Test:" & vbLf)

			' Connect to the asterisk server.
			Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
			Dim serverEndPoint As New IPEndPoint(IPAddress.Parse("192.168.0.20"), 5038)
			clientSocket.Connect(serverEndPoint)

			' Login to the server; manager.conf needs to be setup with matching credentials.
			clientSocket.Send(Encoding.ASCII.GetBytes("Action: Login" & vbCr & vbLf & "Username: mark" & vbCr & vbLf & "Secret: mysecret" & vbCr & vbLf & "ActionID: 1" & vbCr & vbLf & vbCr & vbLf))

			Dim bytesRead As Integer = 0


			Do
				Dim buffer As Byte() = New Byte(1023) {}
				bytesRead = clientSocket.Receive(buffer)

				'Console.WriteLine(bytesRead + " bytes from asterisk server.");

				Dim response As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
				Console.WriteLine(response)

				If Regex.Match(response, "Message: Authentication accepted", RegexOptions.IgnoreCase).Success Then
					' Send a ping request the asterisk server will send back a pong response.
					clientSocket.Send(Encoding.ASCII.GetBytes("Action: Ping" & vbCr & vbLf & "ActionID: 2" & vbCr & vbLf & vbCr & vbLf))
				End If
			Loop While bytesRead <> 0

			Console.WriteLine("Connection to server lost.")
			Console.ReadLine()
		End Sub
	End Class
End Namespace
 
Last edited by a moderator:
I'm not really sure why an example is required. You handle the DataReceived event and you call the ReadLine method to read a line. If you want to read more than one line then you call ReadLine more than once. I think that you're trying to make this harder than it is. The DataReceived event is raised when data is received and the ReadLine method reads a line, exactly as the names suggest.
 
I'm not really sure why an example is required. You handle the DataReceived event and you call the ReadLine method to read a line. If you want to read more than one line then you call ReadLine more than once. I think that you're trying to make this harder than it is. The DataReceived event is raised when data is received and the ReadLine method reads a line, exactly as the names suggest.

Ok, my concern is whether this is the correct approach. I am finally at a computer so maybe I can explain better.

So my socket puts out the following data.


VB.NET:
Response: Success
Message: Authentication accepted

Event: FullyBooted
Privilege: system,all
Status: Fully Booted


Response: Error
Message: Missing action in request


Response: Error
Message: Missing action in request



I need to evaluate each block of text (the start of the text up until the blank line. Do you think the readline evaluating for the carriage return is the correct approach?

Thanks!
 
I was able to handle properly by using the streamreader.


VB.NET:
        Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim serverEndPoint As New IPEndPoint(IPAddress.Parse("192.168.5.55"), 5038)
        clientSocket.Connect(serverEndPoint)

        Dim ns As New System.Net.Sockets.NetworkStream(clientSocket)

        Dim sw As New System.IO.StreamWriter(ns)
        sw.Write("Action:Login" & vbCrLf)
        sw.Write("Username: vinnie" & vbCrLf)
        sw.Write("Secret: 12345" & vbCrLf)
        sw.Write("ActionID: 1" & vbCrLf & vbCrLf)
        sw.Flush()
        'sw.Close()

        Dim sr As New System.IO.StreamReader(ns)
        Dim line As String = ""
        line = sr.ReadLine

        Dim sb As New StringBuilder


        Do While (Not line Is Nothing)
            ' Add this line to list.

            ' Display to console.
            ' Console.WriteLine(line)
            If line = "" Then
                processevent(sb.ToString) 'My function to process whole text.
                sb.Length = 0
            End If

            ' Read in the next line.
            line = sr.ReadLine
            sb.Append(line & vbCrLf)
        Loop
        sr.Close()
 
Back
Top