I'm trying to write a DLL file to handle sockets for my UWP apps, much like I did for my winforms apps. Problem is I'm just getting into writing UWP apps. My original socket control DLL file would start a receive thread, and every 100 milliseconds, read from the socket and raise an event. I tried doing the same thing in my UWP DLL, but it doesn't seem to work with the code I copied from the MSDN website. Can someone take a look and see what I'm doing wrong? I'm not going to lie, I've never used a task before (threads seemed easier).
PS, I've confirmed that connecting and sending data works.
EDIT: Changed my code slightly. But still doesn't work. Any ideas folks?
Doesn't seem to be going past the below line, even when data is sent to it.
Dim DataText As String = Reader.ReadToEnd
Imports Windows.Networking
Imports Windows.Networking.Sockets
Public Class ClientSocket
Private CSocket As New StreamSocket
Dim strHost As String = "192.168.0.11"
Dim RPort As String = "80"
Private killswitch As Boolean = False
Public Event SocketError(ByVal Operation As String, ByVal ErrorMessage As String)
Public Event DataReceived(ByVal DataString As String)
Public Async Sub Connect()
Try
Dim RHost As HostName = New HostName(strHost)
Await CSocket.ConnectAsync(RHost, RPort)
ReceiveTask.Start()
Catch ex As Exception
RaiseEvent SocketError("Connecting", ex.Message)
End Try
End Sub
Public Sub Disconnect()
killswitch = True
CSocket.Dispose()
End Sub
Public Async Sub SendText(ByVal SendString As String)
Try
Dim OutStream As Stream = CSocket.OutputStream.AsStreamForWrite
Dim Writer As StreamWriter = New StreamWriter(OutStream)
Await Writer.WriteLineAsync(SendString)
Await Writer.FlushAsync
Catch ex As Exception
RaiseEvent SocketError("Sending", ex.Message)
End Try
End Sub
Private ReceiveTask As New Task(Sub()
Dim InStream As Stream = CSocket.InputStream.AsStreamForRead
Dim Reader As StreamReader = New StreamReader(InStream)
While killswitch = False
Try
Dim DataText As String = Reader.ReadToEnd
RaiseEvent DataReceived(DataText)
Catch ex As Exception
RaiseEvent SocketError("Receiving", ex.Message)
End Try
Task.Delay(TimeSpan.FromSeconds(1))
End While
End Sub)
Public Property Host As String
Get
Host = strHost
End Get
Set(value As String)
strHost = value
End Set
End Property
Public Property Port As String
Get
Port = RPort
End Get
Set(value As String)
RPort = value
End Set
End Property
End Class
Solved with the below code in the Receive Task:
Private ReceiveTask As New Task(Sub()
Dim InStream As Stream = CSocket.InputStream.AsStreamForRead
While killswitch = False
Try
Dim Reader As StreamReader = New StreamReader(InStream)
Dim DataText As String = ""
While Reader.Peek <> -1
DataText &= Convert.ToChar(Reader.Read)
End While
RaiseEvent DataReceived(DataText)
Catch ex As Exception
RaiseEvent SocketError("Receiving", ex.Message)
End Try
End While
End Sub)