I have gone through the Link vb serial communication. They ar eusing below function for getting data. My question are as follows
How to call this below function on VB
My data from serial are CSV value how to separate and display in a text box
Updating the text box values?
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
MY compelte code aS BELOW
Imports System
Imports System.IO.Ports
Imports System.ComponentModel
Imports System.Threading
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim myPort As Array
myPort = IO.Ports.SerialPort.GetPortNames()
PortComboBox.Items.AddRange(CType(myPort, Object()))
BaudComboBox.Items.Add(9600)
BaudComboBox.Items.Add(19200)
BaudComboBox.Items.Add(38400)
BaudComboBox.Items.Add(57600)
BaudComboBox.Items.Add(115200)
ConnectButton.Enabled = True
DisconnectButton.Enabled = False
Timer1.Interval = 1000
Timer1.Start()
Receive.Text = ReceiveSerialData()
End Sub
Private Sub ConnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectButton.Click
SerialPort1.PortName = PortComboBox.Text
SerialPort1.BaudRate = CInt(BaudComboBox.Text)
SerialPort1.Open()
Timer1.Start()
'lblMessage.Text = PortComboBox.Text & " Connected."
ConnectButton.Enabled = False
DisconnectButton.Enabled = True
End Sub
Private Sub DisconnectButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectButton.Click
SerialPort1.Close()
DisconnectButton.Enabled = False
ConnectButton.Enabled = True
End Sub
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com3 As IO.Ports.SerialPort = Nothing
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.ReadTimeout = 10000
Do
Dim Incoming As String = com3.ReadLine()
If Incoming Is Nothing Then
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
Return returnStr
End Function
End Class
i am trying to create a short sample for you but you need to understand threading and serial working for this. follow the steps to create this sample
add new class module to your code with name mySerial and past following code in it (replace code)
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel
Public Class dataReceivedEventArgs
Inherits EventArgs
Private m_StringData As String
Public Sub New(strData As String)
Me.m_StringData = strData
End Sub
Public ReadOnly Property ReceivedData As String
Get
Return m_StringData
End Get
End Property
End Class
Public Class mySerial
Private ReadThread As Thread
Dim SPort As SerialPort
Private syncContext As SynchronizationContext
Public Event DataReceived(Sender As Object, ByVal e As dataReceivedEventArgs)
Public Sub New(ByVal COMMPORT As String, ByVal BaudRate As Integer)
Me.New(COMMPORT, BaudRate, Parity.None, 8, StopBits.One)
End Sub
Public Sub New(ByVal _COMMPORT As String, ByVal _BaudRate As Integer, ByVal _Parity As Parity, ByVal _DataBits As Integer, ByVal _StopBits As StopBits)
SPort = New SerialPort
With SPort
.PortName = _COMMPORT
.BaudRate = _BaudRate
.Parity = _Parity
.DataBits = _DataBits
.StopBits = _StopBits
.Handshake = Handshake.XOnXOff
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
Me.syncContext = AsyncOperationManager.SynchronizationContext
ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Sub OpenPort()
If Not SPort.IsOpen Then
SPort.Open()
SPort.DiscardNull = True
SPort.Encoding = System.Text.Encoding.ASCII
ReadThread.Start()
End If
End Sub
Public Sub ClosePort()
If SPort.IsOpen Then
SPort.Close()
End If
End Sub
Private Sub ReadPort()
Do While SPort.IsOpen
Dim ReceviceData As String = String.Empty
Do While SPort.BytesToRead <> 0 And SPort.IsOpen And ReceviceData.Length < 5000
Try
ReceviceData &= SPort.ReadExisting()
Thread.Sleep(100)
Catch ex As Exception
End Try
Loop
If ReceviceData <> String.Empty Then
'raise event and provide data
syncContext.Post(New SendOrPostCallback(AddressOf onDataReceived), ReceviceData)
End If
Thread.Sleep(500)
Loop
End Sub
Private Sub onDataReceived(ByVal ReceivedData As String)
RaiseEvent DataReceived(Me, New dataReceivedEventArgs(ReceivedData))
End Sub
End Class
this is class which will work as wrapper class for you, now to make it work add a form with name frmSerial and a textBox with name txtData and set multiline=true, scrollbars=both, now past following code in it
Public Class frmSerial
Dim WithEvents _Serial As mySerial
Private Sub frmSerial_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
_Serial.ClosePort()
End Sub
Private Sub frmSerial_Shown(sender As Object, e As EventArgs) Handles Me.Shown
_Serial = New mySerial("COM1", 9600)
_Serial.OpenPort()
End Sub
Private Sub _Serial_DataReceived(Sender As Object, e As dataReceivedEventArgs) Handles _Serial.DataReceived
txtData.Text &= e.ReceivedData
txtData.SelectionStart = txtData.Text.Length
txtData.ScrollToCaret()
End Sub
End Class
hop this helps you and people like you
Related
I want to download multiples files and the download links in list box, Is there any way to do that using WebClient, i saw people do that by download file by file by it look difficult way and i want to show current downloading speed ,current file size and progress of total process
I solved this proplem by that way:
Imports System.Net
Public Class Form1
Private WithEvents DonloadFile As WebClient
Dim stopwatch As Stopwatch = New Stopwatch
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.SelectedIndex = 0
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
stopwatch.Start()
DonloadFile = New WebClient
Try
DonloadFile.DownloadFileAsync(New Uri(ListBox1.SelectedItem.ToString), "C:\Users\" & Environment.UserName & "\Desktop\" & IO.Path.GetFileName(ListBox1.SelectedItem.ToString))
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub DonloadFile_DownloadProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs) Handles DonloadFile.DownloadProgressChanged
Dim y As Integer = (e.BytesReceived / 1024) / 1024
Label6.Text = "Download Speed: " & String.Format("{0} MB/s", (y / (stopwatch.Elapsed.TotalSeconds)).ToString("0.00"))
Label2.Text = "Current File Size: " & Math.Round(e.TotalBytesToReceive / (1024 * 1024), 1) & " MB"
Label3.Text = "Current File Persent: " & e.ProgressPercentage
Label1.Text = "Total Files: " & ListBox1.Items.Count.ToString()
If ListBox1.Items.Count.ToString > (ListBox1.SelectedIndex + 1) Then
If e.ProgressPercentage = 100 Then
ListBox1.SelectedIndex += 1
End If
Else
MessageBox.Show("Download completed successful", "Info")
End If
End Sub
Private Sub DonloadFile_DownloadDataCompleted(sender As Object, e As DownloadDataCompletedEventArgs) Handles DonloadFile.DownloadDataCompleted
stopwatch.Reset()
End Sub
End Class
thanks for #Fawlty
Here is some code I wrote to demonstrate how you could do this. I created a FileDownloader class as this will allow you to get the source url and destination filename when the download completes. I have also added an event for progress. The problem with just using the WebClient class on its own is that you lose track of which file is being processed in the events.
Imports System.ComponentModel
Imports System.Net
' A class for downloading files, with progress and finished events
Public Class FileDownloader
' Private storage
Private FileURL As String = ""
Private SaveToPath As String = ""
' A class to return our result in
Public Class FileDownloaderFileDownloadedEventArgs
Public Property DownloadedURL As String
Public Property SaveToPath As String
Public Sub New(DownloadedURL As String, SaveToPath As String)
Me.DownloadedURL = DownloadedURL
Me.SaveToPath = SaveToPath
End Sub
End Class
' A class to show progress
Public Class FileDownloaderProgressEventArgs
Public Property DownloadURL As String
Public Property SaveToPath As String
Public Property TotalBytes As Long
Public Property ProgressBytes As Long
Public Property ProgressPercent As Integer
Public Property UserState As Object
Public Sub New(DownloadURL As String, SaveToPath As String, TotalBytes As Long, ProgressBytes As Long, ProgressPercent As Integer, UserState As Object)
Me.DownloadURL = DownloadURL
Me.SaveToPath = SaveToPath
Me.TotalBytes = TotalBytes
Me.ProgressBytes = ProgressBytes
Me.ProgressPercent = ProgressPercent
Me.UserState = UserState
End Sub
End Class
' The event to raise when the file is downloaded
Public Event FileDownloaded(sender As Object, e As FileDownloaderFileDownloadedEventArgs)
' The event to raise when there is progress
Public Event Progress(sender As Object, e As FileDownloaderProgressEventArgs)
' Pass in the URL and FilePath when creating the downloader object
Public Sub New(FileURL As String, SaveToPath As String)
Me.FileURL = FileURL
Me.SaveToPath = SaveToPath
End Sub
' Call Download() to do the work
Public Sub Download()
Using wc As New WebClient
AddHandler wc.DownloadFileCompleted, AddressOf DownloadFileCompleted
AddHandler wc.DownloadProgressChanged, AddressOf DownloadProgressChanged
wc.DownloadFileAsync(New Uri(FileURL), SaveToPath)
End Using
End Sub
' Catch the download complete and raise our event
Private Sub DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
RaiseEvent Progress(Me, New FileDownloaderProgressEventArgs(FileURL, SaveToPath, e.TotalBytesToReceive, e.BytesReceived, e.ProgressPercentage, e.UserState))
End Sub
Private Sub DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
' Some code you want to run after each file has downloaded
RaiseEvent FileDownloaded(Me, New FileDownloaderFileDownloadedEventArgs(FileURL, SaveToPath))
End Sub
End Class
#Region "How to use the FileDownloader class"
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Loop the URLs in the ListBox
For Each item In ListBox1.Items
' Create a FileDownloader object to handler each one
Dim FD = New FileDownloader(item, "c:\temp\" & IO.Path.GetFileName(item))
' Attach the event handlers
AddHandler FD.FileDownloaded, AddressOf FileDownloaded
AddHandler FD.Progress, AddressOf Progress
' Start the download
FD.Download()
Next
End Sub
' Event handler for file download completed
Private Sub FileDownloaded(sender As Object, e As FileDownloader.FileDownloaderFileDownloadedEventArgs)
tb_Log.AppendText(e.DownloadedURL & " Downloaded To: " & e.SaveToPath & vbCrLf)
End Sub
' Event handler for progress
Private Sub Progress(sender As Object, e As FileDownloader.FileDownloaderProgressEventArgs)
tb_Log.AppendText(IO.Path.GetFileName(e.DownloadURL) & " " & e.ProgressPercent & "% downloaded" & vbCrLf)
End Sub
#End Region
I have made a small LAN messenger and I tried it with two pc's and it didnt work however running two of the applications with one listening to port 40004 and writing to 40005 and one listening to 40005 and writing to 40004 works.
The problem seems to be in the sendb_click where I send the message. It says Receipent not connected.
Error message:
System.net.sockets.socketexception (0x80004005); No connection could be made
because the target machine actively refused it 127.0.0.1:40003
at system.net.sockets.tcpclient..ctor(string hostname,int32 port)
at messenger.form2.sendb_click(object sender, eventargs e) in
D:\Messenger\Messenger\Form2.vb:line 97
:Interface
When connected you can choose a computer that is connected to the network on the right and message it. Im planning on having generated ports or whatever but for testing ive just made 40004 and 40005 the ports.
What is going wrong? Do i have to port forward or something?
below is my code
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Imports System.Net.Dns
Imports System.DirectoryServices
Public Class Form2
Class entity
Public name As String
Public ip As String
Public port As Integer
End Class
Public reciepent As New entity
Public user As New entity
Public CLient As New TcpClient
Public listener As New TcpListener(40003)
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
usernametb.Text = user.name
FindingThreats()
getmyip()
ipl.Text = user.ip
user.port = 40003
portl.Text = user.port
' listener = New TcpListener(40004)
Dim ListThread As New Thread(New ThreadStart(AddressOf Listening))
ListThread.Start()
End Sub
Private Sub Listening()
listener.Start()
End Sub
Sub FindingThreats()
UsersL.Items.Clear()
Dim childEntry As DirectoryEntry
Dim ParentEntry As New DirectoryEntry
Try
ParentEntry.Path = "WinNT:"
For Each childEntry In ParentEntry.Children
Select Case childEntry.SchemaClassName
Case "Domain"
Dim SubChildEntry As DirectoryEntry
Dim SubParentEntry As New DirectoryEntry
SubParentEntry.Path = "WinNT://" & childEntry.Name
For Each SubChildEntry In SubParentEntry.Children
Select Case SubChildEntry.SchemaClassName
Case "Computer"
UsersL.Items.Add(SubChildEntry.Name)
End Select
Next
End Select
Next
Catch Excep As Exception
MsgBox("Error While Reading Directories : " + Excep.Message.ToString)
Finally
ParentEntry = Nothing
End Try
End Sub
Sub getmyip()
For Each ip As Net.IPAddress In
GetHostEntry(GetHostName).AddressList
user.ip = ip.ToString
Next
End Sub
Sub getip(strhostname As String, returnip As String)
Try
returnip = GetHostByName(strhostname).AddressList(0).ToString()
reciepent.ip = returnip
Catch
MsgBox("This user is Offline.")
End Try
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles UsersL.SelectedIndexChanged
CUL.Items.Clear()
CUL.Items.Add("Connected Users:")
Dim ip As String
Dim hostname = UsersL.SelectedItem.ToString
getip(hostname, ip)
reciepent.port = 40004
Timer1.Enabled = True
CUL.Items.Add(user.name)
End Sub
Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
Me.Close()
End Sub
Private Sub SendB_Click(sender As Object, e As EventArgs) Handles SendB.Click
Try
CLient = New TcpClient("127.0.0.1", 40004) 'reciepent.port)
Dim Writer As New StreamWriter(CLient.GetStream())
Writer.Write(ChatB.Text)
ChatL.Items.Add("> " & ChatB.Text)
Writer.Flush()
Catch
MsgBox("Receipent not connected.")
End Try
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim message As String
If listener.Pending = True Then
message = ""
CLient = listener.AcceptTcpClient()
Dim Reader As New StreamReader(CLient.GetStream())
While Reader.Peek > -1
message = message + Convert.ToChar(Reader.Read()).ToString
End While
ChatL.Items.Add("< " & message)
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
FindingThreats()
End Sub
Private Sub Form2_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
listener.Stop()
Me.Close()
End Sub
End Class
My program is hangs when sending a messsage my code show no error and when i am testing my gsm shield in hyperterminal i can send message and recieve it through my phone using AT commands. But in my program it just freezes.
Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
Public Class Form1
'connect your mobile/GSM modem to PC,
'then go in device manager and check under ports which COM port has been slected
'if say com1 is there then put com2 in following statement
Dim SMSEngine As New SMSCOMMS("COM4")
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
SMSEngine.SendSMS() 'send the SMS
End Sub
End Class
Public Class SMSCOMMS
Private WithEvents SMSPort As SerialPort
Private SMSThread As Thread
Private ReadThread As Thread
Shared _Continue As Boolean = False
Shared _ContSMS As Boolean = False
Private _Wait As Boolean = False
Shared _ReadPort As Boolean = False
Public Event Sending(ByVal Done As Boolean)
Public Event DataReceived(ByVal Message As String)
Public Sub New(ByRef COMMPORT As String)
'initialize all values
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 9600
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
End Sub
Public Function SendSMS() As Boolean
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Function
Public Sub Open()
If Not SMSPort.IsOpen Then
SMSPort.Open()
End If
End Sub
Public Sub Close()
If SMSPort.IsOpen Then
SMSPort.Close()
End If
End Sub
End Class
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SMSEngine.Open() 'open the port
If Not BackgroundWorker1.IsBusy Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
If SMSPort.IsOpen = True Then
'sending AT commands
SMSPort.WriteLine("AT")
SMSPort.WriteLine("AT+CMGF=1" & vbCrLf) 'set command message format to text mode(1)
SMSPort.WriteLine("AT+CSCA="" +639170000130""" & vbCrLf) 'set service center address (which varies for service providers (idea, airtel))
SMSPort.WriteLine("AT+CMGS= + TextBox1.text + " & vbCrLf) ' enter the mobile number whom you want to send the SMS
_ContSMS = False
SMSPort.WriteLine("+ TextBox1.text +" & vbCrLf & Chr(26)) 'SMS sending
MessageBox.Show(":send")
SMSPort.Close()
End If
End Sub
I am new in stock trading application and I am working on this application since last 9 months in vb.net
I am successful to display real time data in listview and I used threadpool to complete this task but when application display real time stock quotes, system CPU usage goes to high (around 30 to 45%) so how can I reduce tends to 0 to 5%
I visited this link Real-Time-Data-Grid but I am not exactly satisfied with this link (but it is useful for C# only) so any perfect suggestion in vb.net.?
And in my application I am reading real time data from excel sheet of third party software. So I want to know that is COM reading in vb.net heavy loaded process.?
Or If any other suggestion for free real time tick to tick data API of indian stock market excepting Google finance and Yahoo finance
Here it is code:
I define class for real time data feed which named RTDFeed.vb
Imports System.Data.OleDb
Imports Microsoft.Win32
Imports System.Security
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Imports System.Threading
Imports System.ComponentModel
Imports System.Windows
Imports System.Windows.Forms
Imports System.Drawing.Color
Imports System.Net
Imports System.Data.SqlClient
Imports System.Drawing
Public Class RTDFeed
''Class varialbal Data
Private SyncRoot As New Object()
Private _numRow As Integer = 0
Private _stTime As DateTime
Private _EndTime As DateTime
Private _Exchg As String = String.Empty
Private _Description As String = String.Empty
Private _ScpCode As String = String.Empty
Private _Connfrom As String = String.Empty
Private _IsRunning As Boolean = False
Private _EventStopped As EventWaitHandle
''Delegates and Event
Public Event OnRowUpdate As RowUpdateEventHandler
Public Delegate Sub RowUpdateEventHandler(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
Public Event OnStarted As OnStartedHandler
Public Delegate Sub OnStartedHandler(ByVal Sender As System.Object, ByVal e As EventArgs)
Public Event OnStopped As OnStoppedHandler
Public Delegate Sub OnStoppedHandler(ByVal Sender As System.Object, ByVal e As EventArgs)
''Public constructor
Public Sub New(ByVal numrow As Integer, ByVal Excg As String, ByVal Description As String, ByVal ConnFrom As String, ByVal ScpCode As String)
Me._numRow = numrow
Me._Exchg = Excg
Me._Description = Description
Me._ScpCode = ScpCode
Me._Connfrom = ConnFrom
Me._EventStopped = New ManualResetEvent(False)
End Sub
Public Sub New(ByVal numrow As Integer, ByVal Excg As String, ByVal Description As String, ByVal ConnFrom As String)
Me._numRow = numrow
Me._Exchg = Excg
Me._Description = Description
Me._ScpCode = ScpCode
Me._Connfrom = ConnFrom
Me._EventStopped = New ManualResetEvent(False)
End Sub
''Public Method
Public Sub StartProc()
SyncLock Me.SyncRoot
If Not Me._IsRunning Then
Me._EventStopped.Reset()
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Me.ThreadGetstockproc))
End If
End SyncLock
End Sub
Public Sub StopAsync()
Dim Ts As New ThreadStart(AddressOf Me.StopProc)
Dim Thd As New Thread(Ts)
Thd.Start()
End Sub
''Private Method
Private Sub StopProc()
SyncLock Me.SyncRoot
If Me._IsRunning Then
Me._IsRunning = False
Me._EventStopped.WaitOne()
RaiseEvent OnStopped(Me, EventArgs.Empty)
End If
End SyncLock
End Sub
Private Sub ThreadGetstockproc(ByVal stateinfo As Object)
Me._IsRunning = True
RaiseEvent OnStarted(Me, EventArgs.Empty)
Try
While Not Thread.CurrentThread.ThreadState = ThreadState.AbortRequested
'Me._stTime = DateTime.Now
If Me.GetStock.Count > 0 Then
RaiseEvent OnRowUpdate(Nothing, New RowUpdateEventArgs(Me._numRow, Me.GetStock))
End If
'Dim Ts As TimeSpan = Me._EndTime - Me._stTime
'Dim delay As Integer = Ts.Milliseconds
Thread.Sleep(250) 'delay)
If Not Me._IsRunning Then
Thread.CurrentThread.Abort()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
Me._EventStopped.Set()
End Try
End Sub
Dim i As Double = 0
Private Function GetStock() As List(Of Double)
Dim CelUpdt As New List(Of Double)
Dim Querystr As String = ""
Dim cmd As OleDbCommand
Dim Chang As Double
i += 1
CelUpdt.Clear()
Querystr = "Select F1,F2,F4,F5,F6,F7,F12,F15,F16,F18 From [Sheet1$] Where Trim(F1)='" & Me._Exchg & "' And Trim(F2)='" & Me._Description & "' And Trim(F3)='" & Me._ScpCode & "'"
cmd = New OleDbCommand(Querystr, Excelcn)
Dim FReader As OleDbDataReader
FReader = cmd.ExecuteReader()
If FReader.HasRows Then
FReader.Read()
'Market Value
CelUpdt.Add(CDbl(Val(FReader.Item("F4"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F5"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F6"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F7"))))
CelUpdt.Add(i) 'CDbl(Val(FReader.Item("F12"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F15"))))
CelUpdt.Add(CDbl(Val(FReader.Item("F16"))))
Chang = ((CDbl(FReader.Item("F12")) - CDbl(FReader.Item("F18"))) / CDbl(FReader.Item("F12"))) * 100
CelUpdt.Add(Chang)
FReader.Close()
End If
'Me._EndTime = DateTime.Now
Return CelUpdt
End Function
''Class property
Public Property Numrow() As Integer
Get
Return Me._numRow
End Get
Set(ByVal value As Integer)
Me._numRow = value
End Set
End Property
Public Property Exchg() As String
Get
Return Me._Exchg
End Get
Set(ByVal value As String)
Me._Exchg = value
End Set
End Property
Public Property Desciption() As String
Get
Return Me._Description
End Get
Set(ByVal value As String)
Me._Description = value
End Set
End Property
Public Property ScpCode() As String
Get
Return Me._ScpCode
End Get
Set(ByVal value As String)
Me._ScpCode = value
End Set
End Property
Public Property ConnFrom() As String
Get
Return Me._Connfrom
End Get
Set(ByVal value As String)
Me._Connfrom = value
End Set
End Property
Public Property Isrunning() As Boolean
Get
Return Me._IsRunning
End Get
Set(ByVal value As Boolean)
Me._IsRunning = value
End Set
End Property
End Class
Public Class RowUpdateEventArgs
Inherits System.EventArgs
''class variabal Data
Private _ActiveRow As Integer
Private _CellCollection As New List(Of Double)
''Public Constructor
Public Sub New(ByVal ActRow As Integer, ByVal CellArray As List(Of Double))
_ActiveRow = ActRow
_CellCollection = CellArray
End Sub
''Public Property
Public Property ActiveRow() As Integer
Get
Return Me._ActiveRow
End Get
Set(ByVal value As Integer)
Me._ActiveRow = value
End Set
End Property
Public Property CellCollection() As List(Of Double)
Get
Return Me._CellCollection
End Get
Set(ByVal value As List(Of Double))
Me._CellCollection = value
End Set
End Property
End Class
And on a main Watch I update UI thread mean update listview Cell on OnRowupdateEventArgs
Main watch form its named watch.vb
Imports System.Data.OleDb
Imports Microsoft.Win32
Imports System.Security
Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Text
Imports System.Security.AccessControl
Imports System.Threading
Imports System.ComponentModel
Imports System.Windows
Imports System.Windows.Forms
Imports System.Drawing.Color
Imports System.Net
Imports System.Data.SqlClient
Imports System.Drawing
Public Class FrmWatch
Private Sub FrmWatch_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Me.MdiParent = FrmMainscreen
Me.Icon = FrmMainscreen.Icon
Me.Width = FrmMainscreen.Width - 13
'Me.DoubleBuffered = True
LoadBackgroundWorker.WorkerReportsProgress = True
LoadBackgroundWorker.WorkerSupportsCancellation = True
FrmMainscreen.submnubuyorder.Enabled = True
FrmMainscreen.subnusellorder.Enabled = True
FrmMainscreen.submnupendingorder.Enabled = True
FrmMainscreen.ConformOrderTradeBookToolStripMenuItem.Enabled = True
FrmMainscreen.MktPicToolStripMenuItem.Enabled = True
''Load Market Column created
LoadFileFormat()
LVW.Items.Clear()
LVW.Buffer()
LVW.Columns.Add("Exchang", Clm_exchg, HorizontalAlignment.Left)
LVW.Columns.Add("Symbol", Clm_scrpt, HorizontalAlignment.Left)
LVW.Columns.Add("Ser/Exp", Clm_ExpDT, HorizontalAlignment.Left)
LVW.Columns.Add("Buy Qty", Clm_bqty, HorizontalAlignment.Right)
LVW.Columns.Add("Buy Price", Clm_bPric, HorizontalAlignment.Right)
LVW.Columns.Add("Sell Price", Clm_spric, HorizontalAlignment.Right)
LVW.Columns.Add("Sell Qty", Clm_sqty, HorizontalAlignment.Right)
LVW.Columns.Add("Last Traded Price", Clm_ltPtic, HorizontalAlignment.Right)
LVW.Columns.Add("High", Clm_high, HorizontalAlignment.Right)
LVW.Columns.Add("Low", Clm_low, HorizontalAlignment.Right)
LVW.Columns.Add("Open", Clm_open, HorizontalAlignment.Right)
LVW.Columns.Add("Close", Clm_close, HorizontalAlignment.Right)
LVW.Columns.Add("%Change", Clm_chg, HorizontalAlignment.Right)
LVW.Columns.Add("Trand", Clm_Trnd, HorizontalAlignment.Center)
LVW.Columns.Add("Scrip Code", Clm_ScpCode, HorizontalAlignment.Left)
LVW.SuspendLayout()
''call backgroundworker for Load Mkt
LoadBackgroundWorker.RunWorkerAsync()
If FrmPendingOrder.Visible = True Then
AddHandler Me.UpdatePendingOrd, AddressOf FrmPendingOrder.UpdatePendingOrderTimerFilter
End If
If FrmConformOrder.Visible = True Then
AddHandler Me.UpdateConformOrd, AddressOf FrmConformOrder.RefreshTrade
End If
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace, Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Sub LoadBackgroundWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles LoadBackgroundWorker.DoWork
Try
LoadMarket()
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace,Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Sub LoadBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles LoadBackgroundWorker.RunWorkerCompleted
Try
LVW.ResumeLayout()
If LVW.Items.Count > 0 Then
LVW.Focus()
Me.LVW.Items(0).Selected = True
End If
For i As Integer = 0 To Me.LVW.Items.Count - 1
If Me.LVW.Items(i).Text <> String.Empty And Me.LVW.Items(i).SubItems(1).Text <> String.Empty Then
Dim RTDF As New RTDFeed(i, Me.LVW.Items(i).Text, FeedDesc, CnFrm, Me.LVW.Items(i).SubItems(14).Text)
AddHandler RTDF.OnRowUpdate, AddressOf Me.OnRTDFeedRowUpdat
RTDFeed_Obj.Add(RTDF)
MAX_FEED += 1
End If
Next
For j As Integer = 0 To MAX_FEED - 1
If Not RTDFeed_Obj(j).Isrunning Then
RTDFeed_Obj(j).StartProc()
End If
Next
Catch ex As Exception
ErrorHandler(ex, ex.StackTrace,Reflection.MethodBase.GetCurrentMethod.ToString)
End Try
End Sub
Private Delegate Sub OnRTDFeedRowUpdateHandler(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
Private Sub OnRTDFeedRowUpdat(ByVal sender As System.Object, ByVal e As RowUpdateEventArgs)
If Me.InvokeRequired Then
Me.Invoke(New OnRTDFeedRowUpdateHandler(AddressOf Me.OnRTDFeedRowUpdat), New Object() {sender, e})
Return
End If
RowUpdate(e)
End Sub
Private Sub RowUpdate(ByVal e As RowUpdateEventArgs)
SyncLock Me.SyncRoot
Try
'LVW.Items(e.ActiveRow).SubItems(3).Text = e.CellCollection(0).ToString
'LVW.Items(e.ActiveRow).SubItems(4).Text = CellArray.Item(1).ToString()
'LVW.Items(e.ActiveRow).SubItems(6).Text = CellArray.Item(2).ToString()
'LVW.Items(e.ActiveRow).SubItems(5).Text = CellArray.Item(3).ToString()
LVW.Items(e.ActiveRow).SubItems(7).Text = e.CellCollection(4).ToString 'CellArray.Item(4).ToString()
'LVW.Items(e.ActiveRow).SubItems(8).Text = CellArray.Item(5).ToString()
'LVW.Items(e.ActiveRow).SubItems(9).Text = CellArray.Item(6).ToString()
'LVW.Items(e.ActiveRow).SubItems(12).Text = CellArray.Item(7).ToString()
Catch ex As IndexOutOfRangeException
MsgBox(ex.Message)
End Try
End SyncLock
End Sub
Now My Custom Listview class Named My_Grid which is flicker free listview while updating a cell real time.
Public Class My_GRID
Inherits ListView
Public Sub Buffer()
Me.DoubleBuffered = True
End Sub
End Class
I'm trying con build a simple chat client/software (whole in on executable) wich start listen from the start on the port 5900 and when a client connect to that port the chat is established.
The problem is that only the client can chat to the server, the server cannot answer the client because the connection is working in one way.
The i've tried to connect from "server" to the client when it establishes a connection but the system crash warning me that the port is already on use.
This my code: (working in one way)
Imports System.Net.Sockets
Imports System.Text
Imports System.Reflection
Public Class frmComplete
Dim Data As Integer
Dim Message As String
Private sServer As TcpListener
Private sClient As New TcpClient
Private cServer As TcpListener
Private cClient As New TcpClient
Private cNick As String
Dim BufferSize(1024) As Byte
Private Delegate Sub MessageDelegate(ByVal Message As String)
Private Sub frmComplete_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
srvListen(5900)
btnSend.Enabled = False
End Sub
Private Sub OnServerConnect(ByVal AR As IAsyncResult)
sClient = sServer.EndAcceptTcpClient(AR)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
My.Computer.Audio.Play(Application.StartupPath & "\Connected.wav", AudioPlayMode.Background)
End Sub
Private Sub OnRead(ByVal AR As IAsyncResult)
Data = sClient.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sClient.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnRead, Nothing)
End Sub
Private Sub PrintMessage(ByVal Message As String)
Try
txtChat.Text = txtChat.Text & Message & vbCrLf
My.Computer.Audio.Play(Application.StartupPath & "\Message.wav", AudioPlayMode.Background)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub srvListen(ByVal port As Integer)
Try
sServer = New TcpListener(System.Net.IPAddress.Any, 5900)
sServer.Start()
'THIS WILL RAISE THE EVENT WHEN A CLIENT IS CONNECTED
sServer.BeginAcceptTcpClient(AddressOf OnServerConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Private Sub txtMessage_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMessage.KeyDown
'FIXME (SOUND T_T)
If e.KeyCode = Keys.Enter Then
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
ConnectToServer(txtIP.Text)
cNick = txtNickname.Text
txtNickname.Enabled = False
txtIP.Enabled = False
btnConnect.Enabled = False
End Sub
Private Sub ConnectToServer(ByVal ipadress As String)
Try
cClient.BeginConnect(ipadress, 5900, AddressOf OnClientConnect, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
If Not String.IsNullOrEmpty(txtMessage.Text) Then
txtChat.Text = txtChat.Text & "Me:" & txtMessage.Text & vbCrLf
SendMessage(cNick & ":" & txtMessage.Text)
End If
End Sub
Private Sub SendMessage(ByVal message As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(message)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub SendCommand(ByVal command As String)
If cClient.Connected = True Then
Dim Writer As New IO.StreamWriter(cClient.GetStream)
Writer.Write(command)
Writer.Flush()
End If
txtMessage.Text = ""
End Sub
Private Sub txtMessage_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtMessage.TextChanged
If Not String.IsNullOrEmpty(txtMessage.Text) Then
btnSend.Enabled = True
Else
btnSend.Enabled = False
End If
End Sub
End Class
What I should do? use two ports? one for write and another to read? And if i need to conect multiple clients to one user? (remember the same exe is server/client)
Please help me =(
You aren't reading any data coming back from the Server. You'll notice in your OnServerConnect method you call the BeginRead -- you will also need to do this for your client in the OnClientConnect method, or you'll get a one way communication. Perhaps this is why you are not seeing any data coming through?
I'm guessing, when your Server sends back the data to the client, you aren't getting a hard-error, just no data.
Just glancing over your code I noticed that you have both a TcpClient and TcpListener for your client and server. You don't need this. Your SERVER will be the TcpListener, and your CLIENT will be the TcpClient. By asking if you should connect back on a different port from the server, you are shortchanging yourself of what the TCP connection really is. Once your TcpClient has connected to the TcpServer, your connection is established. There is no need further to attempt to connect.
You're client code should be something similar to:
Private Sub OnClientConnect(ByVal AR As IAsyncResult)
Try
cClient.EndConnect(AR)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub OnClientRead(ByVal AR As IAsyncResult)
Data = sServer.GetStream.EndRead(AR)
Message = Encoding.ASCII.GetString(BufferSize, 0, Data)
Dim Args As Object() = {Message}
Me.Invoke(New MessageDelegate(AddressOf PrintMessage), Args)
sServer.GetStream.BeginRead(BufferSize, 0, BufferSize.Length, AddressOf OnClientRead, Nothing)
End Sub