Find serial port where my device is connected - vb.net

I'm starting to work with a pinpad.
I need that my program find the port where the pinpad is connected without user interaction.
I tried with:
Dim searcher As New ManagementObjectSearcher("root\cimv2","SELECT * FROM Win32_SerialPort")
For Each queryObj As ManagementObject In searcher.Get()
MsgBox(queryObj("Name"))
Next
but this only give me "COM1" and "COM2" as an answer (My device is connected to COM4)
and with
Dim searcher As New ManagementObjectSearcher("root\cimv2", "SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0")
For Each queryObj As ManagementObject In searcher.Get()
MsgBox(queryObj("Name"))
Next
With this one I can see my device friendly name but I donĀ“t know how to get the port (I receive the names like 'HP printer')
Any idea of how can I get the port that I need?
Thanks in advance

Based on the comments it sounds like your device is a USB device that has a driver that causes it to appear to be (emulates) a serial port attached device. In that case I would use:
My.Computer.Ports.SerialPortNames
to enumerate and loop over all serial ports. Then, one at a time try to open each one and send a command to the device that you know it responds to. Most devices have some kind of heartbeat or keep alive message that they will respond to. Whichever port you get a response on is the port you need to use.

I want to point 2 matters:
1: here is a solution i used for this problem (efficiancy corrections will be appreciated)
I used this soution i used to figure out on which port vx805 verifone pin pad was connected (has a unique device id):
Friend Class pinPadComLocater
Private Shared com As String
Private Const PNPDeviceID = "VID_11CA&PID_0220"
Private Const scope = "root\cimv2"
Public ReadOnly pinPadCom As String = Nothing
Sub New()
If isVX805PinPadConnected() Then
pinPadCom = com
Output.mainLog(Output.pinpadLocationMsg + com)
Else
Output.mainLog(Output.pinpadNotFoundMsg)
End If
End Sub
Private Shared Function queryCom(port As String) As Boolean
Dim query = "SELECT * FROM Win32_PnPEntity WHERE ClassGuid=""{4d36e978-e325-11ce-bfc1-08002be10318}"" AND DeviceID LIKE ""%" + PNPDeviceID + "%"" AND Caption LIKE ""%" + port + "%"""
Dim resp = New ManagementObjectSearcher(scope, query).Get
If resp.Count = 1 Then Return True
For Each queryObj As ManagementObject In resp
For Each prop In queryObj.Properties 'print all data for development purposes
Try
Console.writeline(prop.Name + " : " + queryObj(prop.Name).ToString)
catch ex As Exception
End Try
Next
Next
Return False
End Function
Private Shared Function isVX805PinPadConnected() As Boolean
For Each port In My.Computer.Ports.SerialPortNames
Try
If queryCom(port) Then
com = port
Return True
End If
Catch err As ManagementException
Throw New ConstraintException("An error occurred while querying for WMI data: " & err.Message)
End Try
Next
Throw New ConstraintException("Pin Pad Com Port could not be located")
Return False
End Function
End Class
2: would love more clarifiaction on that:
Then, one at a time try to open each one and send a command to the device that you know it responds to. Most devices have some kind of heartbeat or keep alive message that they will respond to
I would love to see a code example of how you send such a heartbeat check to a pinpad

Related

Already running application now gets socket error 10013

I have an application done in VB.NET that listen on a specific UDP port and answer through the same port to the IP that send the packet.
It was working ok from a couple of years to the last month; now when try to answer crash due to socket error 10013.
I even try an older version that I know it was working too and get the same crash.
I try disabling Microsoft Security Essentials real time protection and Windows firewall and didn't work.
In the code I have the line
MyUdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True)
I have no clue about what to do, I'm lost.
Any idea how to solve this?
Edit:
Here's the code
#Region "UDP Send variables"
Dim GLOIP As IPAddress
Dim GLOINTPORT As Integer
Dim bytCommand As Byte() = New Byte() {}
#End Region
Dim MyUdpClient As New UdpClient()
Private Sub StartUdpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartUdpBtn.Click
If StartUdpBtn.Tag = 0 Then
' If Not UdpOpen Then
StartUdpReceiveThread(CInt(ListeningPortLbl.Text))
'End If
Else
If ThreadReceive.IsAlive Then
ThreadReceive.Abort()
MyUdpClient.Close()
PrintLog("UDP port closed")
StartUdpBtn.Tag = 0
UdpOpen = False
StartUdpBtn.Text = "Start UDP"
End If
End If
If UdpOpen Then
StartUdpBtn.Tag = 1
StartUdpBtn.Text = "Stop UDP"
Else
StartUdpBtn.Tag = 0
StartUdpBtn.Text = "Start UDP"
TimerUDP.Enabled = False
TiempoUDP.Stop()
TiempoUdpLbl.Text = "--:--:--"
End If
End Sub
Private Sub StartUdpReceiveThread(ByVal Port As Integer)
Dim UdpAlreadyOpen As Boolean = False
Try
If Not UdpOpen Then
MyUdpClient = New UdpClient(Port)
MyUdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, True)
UdpAlreadyOpen = True
Else
Me.Invoke(Sub()
TiempoUDP.Restart()
If TimerUDP.Enabled = False Then
TimerUDP.Enabled = True
End If
End Sub)
End If
ThreadReceive = New System.Threading.Thread(AddressOf UdpReceive)
ThreadReceive.IsBackground = True
ThreadReceive.Start()
UdpOpen = True
If UdpAlreadyOpen Then
PrintLog(String.Format("UDP port {0} opened, waiting data...", Port.ToString))
End If
Catch ex As Exception
PrintErrorLog(ex.Message)
PrintErrorLog(ex.StackTrace)
End Try
End Sub
Private Sub UdpReceive()
Dim receiveBytes As [Byte]() = MyUdpClient.Receive(RemoteIpEndPoint)
DstPort = RemoteIpEndPoint.Port
IpRemota(RemoteIpEndPoint.Address.ToString)
Dim BitDet As BitArray
BitDet = New BitArray(receiveBytes)
Dim strReturnData As String = System.Text.Encoding.ASCII.GetString(receiveBytes)
If UdpOpen Then
StartUdpReceiveThread(CInt(ListeningPortLbl.Text))
End If
PrintLog("From: " & RemoteIpLbl.Text & ":" & ListeningPortLbl.Text & " - " & strReturnData)
AnswersProcessor(strReturnData)
End Sub
Private Sub UdpSend(ByVal txtMessage As String)
Dim pRet As Integer
GLOIP = IPAddress.Parse(RemoteIpLbl.Text)
'From UDP_Server3_StackOv
Using UdpSender As New System.Net.Sockets.UdpClient()
Dim RemoteEndPoint = New System.Net.IPEndPoint(0, My.Settings.UDP_Port)
UdpSender.ExclusiveAddressUse = False
UdpSender.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, True)
UdpSender.Client.Bind(RemoteEndPoint)
UdpSender.Connect(GLOIP, DstPort)
bytCommand = Encoding.ASCII.GetBytes(txtMessage)
pRet = UdpSender.Send(bytCommand, bytCommand.Length)
End Using
PrintLog("No of bytes send " & pRet)
End Sub
10013 is WSAEACCES, which is documented as follows:
Permission denied.
An attempt was made to access a socket in a way forbidden by its access permissions. An example is using a broadcast address for sendto without broadcast permission being set using setsockopt(SO_BROADCAST).
Another possible reason for the WSAEACCES error is that when the bind function is called (on Windows NT 4.0 with SP4 and later), another application, service, or kernel mode driver is bound to the same address with exclusive access. Such exclusive access is a new feature of Windows NT 4.0 with SP4 and later, and is implemented by using the SO_EXCLUSIVEADDRUSE option.
In the comments you mentioned:
I tried the program on a XP x32 and works ok but on Windows 7 x32/x64 don't, even if I disable the firewall and Microsoft Security Essentials Live Protection.
Maybe it sounds almost obvious but you could try to start your program in all of the available Windows XP compatibility modes. You didn't say that you already tried this but maybe you're lucky and the problem will be "solved" by this workaround.
If the problem still exists afterwards and considering the error code of 10013, I would try or check the following things:
I know you disabled "Microsoft Security Essentials" and the Windows Firewall, but double check whether there are other security related programs/services like anti virus protection, anti malware tools etc. running. It really sounds like something is blocking your socket creation/bind.
In case your program created log output/data which allows you to see exactly when it started to fail:
Any new software installed at that time?
Were Windows Updates (maybe automatically) installed at that time? Especially security updates regarding network security?
Any other noticeable changes in your environment? What about log entries in your Windows system log?
Just as a little test to verify if the error occurs only with your UDP socket: Try to use a TCP socket instead of UDP.
Start the machine in Windows Safe Mode with network support and execute your program from there.
Run your program on another Windows 7 machine and see if the same problem occurs there. It could be a valuable starting point (in terms of localization) to know if the problem occurs only on specific versions of Windows.
Single step through your code with a debugger and carefully watch what happens. Perhaps this can reveal some additional info on what's going wrong.
Maybe some of the ideas above can help you to track down the problem a little bit more. Good luck!

IRC Client in Visual Basic

Hello I am trying to create a chat bot for my twitch channel in Visual Basic. I did some research and I found this code:
Public Class My_IRC
Private _sServer As String = String.Empty '-- IRC server name
Private _sChannel As String = String.Empty '-- the channel you want to join (prefex with #)
Private _sNickName As String = String.Empty '-- the nick name you want show up in the side bar
Private _lPort As Int32 = 6667 '-- the port to connect to. Default is 6667
Private _bInvisible As Boolean = False '-- shows up as an invisible user. Still working on this.
Private _sRealName As String = "nodibot" '-- More naming
Private _sUserName As String = "nodi_the_bot" '-- Unique name so of the IRC network has a unique handle to you regardless of the nickname.
Private _tcpclientConnection As TcpClient = Nothing '-- main connection to the IRC network.
Private _networkStream As NetworkStream = Nothing '-- break that connection down to a network stream.
Private _streamWriter As StreamWriter = Nothing '-- provide a convenient access to writing commands.
Private _streamReader As StreamReader = Nothing '-- provide a convenient access to reading commands.
Public Sub New(ByVal server As String, ByVal channel As String, ByVal nickname As String, ByVal port As Int32, ByVal invisible As Boolean)
_sServer = server
_sChannel = channel
_sNickName = nickname
_lPort = port
_bInvisible = invisible
End Sub
Public Sub Connect()
'-- IDENT explained:
'-- -- When connecting to the IRC server they will send a response to your 113 port.
'-- -- It wants your user name and a response code back. If you don't some servers
'-- -- won't let you in or will boot you. Once verified it drastically speeds up
'-- -- the connecting time.
'-- -- -- http://en.wikipedia.org/wiki/Ident
'-- Heads up - when sending a command you need to flush the writer each time. That's key.
Dim sIsInvisible As String = String.Empty
Dim sCommand As String = String.Empty '-- commands to process from the room.
'-- objects used for the IDENT response.
Dim identListener As TcpListener = Nothing
Dim identClient As TcpClient = Nothing
Dim identNetworkStream As NetworkStream = Nothing
Dim identStreamReader As StreamReader = Nothing
Dim identStreamWriter As StreamWriter = Nothing
Dim identResponseString As String = String.Empty
Try
'-- Start the main connection to the IRC server.
Console.WriteLine("**Creating Connection**")
_tcpclientConnection = New TcpClient(_sServer, _lPort)
_networkStream = _tcpclientConnection.GetStream
_streamReader = New StreamReader(_networkStream)
_streamWriter = New StreamWriter(_networkStream)
'-- Yeah, questionable if this works all the time.
If _bInvisible Then
sIsInvisible = 8
Else
sIsInvisible = 0
End If
'-- Send in your information
Console.WriteLine("**Setting up name**")
_streamWriter.WriteLine(String.Format("USER {0} {1} * :{2}", _sUserName, sIsInvisible, _sRealName))
_streamWriter.Flush()
'-- Create your nickname.
Console.WriteLine("**Setting Nickname**")
_streamWriter.WriteLine(String.Format(String.Format("NICK {0}", _sNickName)))
_streamWriter.Flush()
'-- Tell the server you want to connect to a specific room.
Console.WriteLine("**Joining Room**")
_streamWriter.WriteLine(String.Format("JOIN {0}", _sChannel))
_streamWriter.Flush()
'-- By now the IDENT should be sent to your port 113. Listen to it, grab the text,
'-- and send a response.
'-- Idents are usually #### , ####
'-- That is four digits, a space, a comma, and four more digits. You need to send
'-- this back with your user name you connected with and your system.
identListener = New TcpListener(IPAddress.Any, 113)
identListener.Start()
identClient = identListener.AcceptTcpClient
identListener.Stop()
Console.WriteLine("ident connection?")
identNetworkStream = identClient.GetStream
identStreamReader = New StreamReader(identNetworkStream)
identResponseString = identStreamReader.ReadLine
Console.WriteLine("ident got: " + identResponseString)
identStreamWriter = New StreamWriter(identNetworkStream)
'-- The general format for the IDENT response. You can use UNIX, WINDOWS VISTA, WINDOWS XP, or what ever your system is.
identStreamWriter.WriteLine(String.Format("{0} : USERID : WINDOWS 7 : {1}", identResponseString, _sUserName))
identStreamWriter.Flush()
'-- By now you should be connected to your room and visible to anyone else.
'-- If you are receiving errors they are pretty explicit and you can maneuver
'-- to debuggin them.
'--
'-- What happens here is the command processing. In an infinite loop the bot
'-- read in commands and act on them.
While True
sCommand = _streamReader.ReadLine
Console.WriteLine(sCommand)
'-- Not the best method but for the time being it works.
'--
'-- Example of a command it picks up
' :nodi123!nodi12312#ipxxx-xx.net PRIVMSG #nodi123_test :? hola!
'-- You can extend the program to better read the lines!
Dim sCommandParts(sCommand.Split(" ").Length) As String
sCommandParts = sCommand.Split(" ")
'-- Occasionally the IRC server will ping the app. If it doesn't respond in an
'-- appropriate amount of time the connection is closed.
'-- How does one respond to a ping, but with a pong! (and the hash it sends)
If sCommandParts(0) = "PING" Then
Dim sPing As String = String.Empty
For i As Int32 = 1 To sCommandParts.Length - 1
sPing += sCommandParts(i) + " "
Next
_streamWriter.WriteLine("PONG " + sPing)
_streamWriter.Flush()
Console.WriteLine("PONG " + sPing)
End If
'-- With my jank split command we want to look for specific commands sent and react to them!
'-- In theory this should be dumped to a method, but for this small tutorial you can see them here.
'-- Also any user can input this. If you want to respond to commands from you only you would
'-- have to extend the program to look for your non-bot-id in the sCommandParts(0)
If sCommandParts.Length >= 4 Then
'-- If a statement is proceeded by a question mark (the semi colon's there automatically)
'-- then repeat the rest of the string!
If sCommandParts(3).StartsWith(":?") Then
Dim sVal As String = String.Empty
Dim sOut As String = String.Empty
'-- the text might have other spaces in them so concatenate the rest of the parts
'-- because it's all text.
For i As Int32 = 3 To sCommandParts.Length - 1
sVal += sCommandParts(i)
sVal += " "
Next
'-- remove the :? part.
sVal = sVal.Substring(2, sVal.Length - 2)
'-- Trim for good measure.
sVal = sVal.Trim
'-- Send the text back out. The format is they command to send the text and the room you are in.
sOut = String.Format("PRIVMSG {0} : You said '{1}'", _sChannel, sVal)
_streamWriter.WriteLine(sOut)
_streamWriter.Flush()
End If
'-- If you don't quit the bot correctly the connection will be active until a ping/pong is failed.
'-- Even if your programming isn't running!
'-- To stop that here's a command to have the bot quit!
If sCommandParts(3).Contains(":!Q") Then
' Stop
_streamWriter.WriteLine("QUIT")
_streamWriter.Flush()
Exit Sub
End If
End If
End While
Catch ex As Exception
'-- Any exception quits the bot gracefully.
Console.WriteLine("Error in Connecting. " + ex.Message)
_streamWriter.WriteLine("QUIT")
_streamWriter.Flush()
Finally
'-- close your connections
_streamReader.Dispose()
_streamWriter.Dispose()
_networkStream.Dispose()
End Try
End Sub
End Class
and
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Public Sub Main()
Dim foo As New My_IRC("irc.freenode.net", "#nodi123_test", "nodime", 6667, False)
foo.Connect()
End Sub
But I can not succeed to connect using a password because it is simply to hard for me as a beginner. (You can either set a password or use the command /server irc.twitch.tv 6667 oauth:AUTHKEY) so my question is, is there a way to set the password in the code I posted? Or is there another stable way to use IRC in Visual Basic which allows me to set a server password? Let me know, thanks.
Your first stop should be the IRC RFC documents, RFC 1459 and 2812. From the snippet of code you provided, your IRC client does not implement the PASS message -- see section 4.1.1 of RFC 1459.
4.1.1 Password message
Command: PASS Parameters: <password>
The PASS command is used to set a 'connection password'. The
password can and must be set before any attempt to register the
connection is made. Currently this requires that clients send a PASS
command before sending the NICK/USER combination and servers must
send a PASS command before any SERVER command. The password supplied
must match the one contained in the C/N lines (for servers) or I
lines (for clients). It is possible to send multiple PASS commands
before registering but only the last one sent is used for
verification and it may not be changed once registered. Numeric
Replies:
ERR_NEEDMOREPARAMS ERR_ALREADYREGISTRED
Example:
PASS secretpasswordhere
It should be relatively easy to implement:
**Console.WriteLine("**Setting Password**")
_streamWriter.WriteLine(String.Format(String.Format("PASS {0}", whateverVariableYouChooseToHoldThePassword)))
_streamWriter.Flush()**
'-- Send in your information
Console.WriteLine("**Setting up name**")
_streamWriter.WriteLine(String.Format("USER {0} {1} * :{2}", _sUserName, sIsInvisible, _sRealName))
_streamWriter.Flush()
I'll take this opportunity to mention that I wrote an IRC library a while back that may help you, at least as a reference point for how IRC behaves. I implemented a decent portion of RFC 1459 before I lost interest. Interestingly enough, my IRC library doesn't support sending the PASS message either (although it would be similarly easy to add support).
My library could theoretically be of use to you as-is, but I don't think it's production ready, so to speak.

USB COM port data reading error

I am using people count device to read the InCount, Out Count record and it is connected with my PC COM3 USB port.. I have written the code to fetch the data, I am continuously receiving the below message while reading the data..... can I have some code or idea to fetch the record?
message is.... The operation has timed out.
mycode is below:
Function ReceiveSerialData() As String
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim com1 As IO.Ports.SerialPort
'SerialPort sp = new SerialPort("COM3", 115200, Parity.None, 8, StopBits.One);
Try
com1 = My.Computer.Ports.OpenSerialPort("COM3")
com1.BaudRate = 115200
com1.ReadTimeout = 10000
Do
Dim Incoming As String = com1.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 com1 IsNot Nothing Then com1.Close()
End Try
Return returnStr
End Function
You must know at least the following 7 parameter settings for the device you are trying to communicate with and set your serial port properties to match.
PortName
BaudRate
Parity
DataBits
StopBits
NewLine
Handshake
Some of these you might guess (Parity is usually none, Databits is usually 8 stop bits is usually 1, handshake is often none). But Hans is correct unless you get all these set properly you will never communicate with your device. Also it is better to open your serial port once during initialization of your program and then leave it open until the program closes.

How do I check if an ftp server is online and get the error that it generates if it is not connected?

I am new to programming in vb.net. I have come a long ways in my development and understanding of vb, but there is one hurtle I can not seem to fix. I am hosting an ftp server on my pc and I am making an app for it to connect to my server and download files. The problem with all the sample code is that everyone ASSUMES the server WILL be ONLINE. My pc may not be running 24/7 and I also may not have the ftp service running.In the first case it shouldnt even register that it is connected. In the second case, it WILL say that is connected b/c the pc is on, but it will return that the machine ou are trying to connect to is actively refusing the connection. Is there a way to TRULY check if the program is indeed connected to the server WITHOUT generating a bunch of Exceptions in the debugger? All I want is a call like:
Dim ftponline As Boolean = False 'Set default to false
ftponline = checkftp()
If ftponline Then
'continue program
Else
'try a different server
End If
So it would be a function called checkftp that returns a boolean value of true or false.
Here is my info:
Using Visual Studio 2010 Pro
Using .Net framework 4
Can anyone help?
Thanks!
I have tried the rebex ftp pack as well as the Ultimate FTP Pack.
Here is the updated code:
Public Function CheckConnection(address As String) As Boolean
Dim logonServer As New System.Net.Sockets.TcpClient()
Try
logonServer.Connect(address, 21)
Catch generatedExceptionName As Exception
MessageBox.Show("Failed to connect to: " & address)
End Try
If logonServer.Connected Then
MessageBox.Show("Connected to: " & address)
Return True
logonServer.Close()
Else
Return False
End If
End Function
Public Sub ConnectFtp()
types.Clear()
models.Clear()
ListBox1.Items.Clear()
ListBox2.Items.Clear()
TextBox2.Clear()
Dim request As New Rebex.Net.Ftp
If CheckConnection(*) Then
Dim tempString As String()
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory("/atc3/HD_Models")
Dim list As Array
list = request.GetNameList()
Dim item As String = ""
For Each item In list
tempString = item.Split(New Char() {" "c})
If types.Contains(tempString(0)) = False Then
types.Add(tempString(0))
End If
If models.Contains(item) = False Then
models.Add(item)
End If
Next
request.Disconnect()
request.Dispose()
ElseIf CheckConnection(*) Then
request.Connect(*)
request.Login(*, *)
request.ChangeDirectory(*)
Dim list2 As Array
list2 = request.GetNameList()
Dim item2 As String = ""
Dim tempString2 As String()
For Each item2 In list2
MessageBox.Show(item2)
tempString2 = item2.Split(New Char() {" "c})
If types.Contains(tempString2(0)) = False Then
types.Add(tempString2(0))
End If
If models.Contains(item2) = False Then
models.Add(item2)
End If
Next
request.Disconnect()
request.Dispose()
End If
End Sub
No matter what I do, the second server will not connect. I even put a messagebox to show what items were being returned in the second server, but there are no messageboxes apearing when I run the program with my server offline. Is there anyone who can help?
If your code is designed with proper exception catching, it shouldn't be generating a "bunch" of exceptions. The first exception you catch should be your indication that the connection failed and your code should cease attempting to communicate at that point. If for some reason you really need to check the connectivity before attempting the FTP connection, you should be able to simply attempt to synchronously open a TCP socket to the FTP server's port. If that works, it's up and running.
You could simply open a socket to the server's IP address on Port 21 (assuming default FTP port).
I'm not much of a VB.Net programmer, but here's a link to sample code:
http://vb.net-informations.com/communications/vb.net_Client_Socket.htm
If you can establish the socket connection, you know that something is listening on that port (though you have not yet proven it's an FTP server, or that it will accept your login credentials...).
If you wish to simply avoid exceptions in the debugger, you could place the connection code in a method and apply the DebuggerHidden attribute to that method.

TCP Server in VB.NET

I am not a software programmer but I have a task to create a TCP Server (a program that is listening on its network card interfaces for incoming data streams).
I have searched on the internet and I found that I can use two methods: Socket or TCPListener class.
I have created an example for the Socket class, but I was wondering how I can test it?
If another computer in the network sends some string data to the listener computer, then the message should be displayed.
Here is the example from Microsoft that I am using for the TCP server using a Socket:
Public Shared Sub Main()
' Data buffer for incoming data.
Dim data = nothing
Dim bytes() As Byte = New [Byte](1024) {}
Dim ipAddress As IPAddress = ipAddress.Any
Dim localEndPoint As New IPEndPoint(ipAddress, 0)
Dim intI As Integer = 0
'Display the NIC interfaces from the listener
For Each ipAddress In ipHostInfo.AddressList
Console.WriteLine("The NIC are {0}", ipHostInfo.AddressList(intI))
intI += 1
Next
Console.WriteLine("You are listening on {0}",localEndPoint)
' Create a TCP/IP socket.
Dim listener As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Bind the socket to the local endpoint and
' listen for incoming connections.
Try
listener.Bind(localEndPoint)
listener.Listen(200)
Catch e As SocketException
Console.WriteLine("An application is alreading using that combination of ip adress/port", e.ErrorCode.ToString)
End Try
' Start listening for connections.
While True
Console.WriteLine("Waiting for a connection...")
' Program is suspended while waiting for an incoming connection.
Dim handler As Socket = listener.Accept()
data = Nothing
' An incoming connection needs to be processed.
While True
bytes = New Byte(1024) {}
Dim bytesRec As Integer = handler.Receive(bytes)
data += Encoding.ASCII.GetString(bytes, 0, bytesRec)
Console.WriteLine("The string captured is {0}", data)
If data.IndexOf("something") > -1 Then
Exit While
End If
End While
' Show the data on the console.
Console.WriteLine("Text received : {0}", data)
' Echo the data back to the client.
Dim msg As Byte() = Encoding.ASCII.GetBytes(data)
handler.Shutdown(SocketShutdown.Both)
handler.Close()
End While
End Sub
End Class
Am I on the right lead?
Thanks
Later Edit:
I have used that code in a Console Application created with Visual Studio and I want to check the scenario when a device is sending some string message through the network.
E.g:
I have two devices :Computer A, computer B connected through LAN
I have tried this command : telnet computerA port ( from computer B) but nothing is displayed in the TCP server running from computer A.
telnet 192.168.0.150 3232
I also made a TCP client for testing (derived from the Microsoft example):
Public Class SynchronousSocketClient
Public Shared Sub Main()
' Data buffer for incoming data.
Dim bytes(1024) As Byte
Dim ipHostInfo As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim ipAddress As IPAddress = ipHostInfo.AddressList(0)
Dim remoteEP As New IPEndPoint(ipAddress, 11000)
' Create a TCP/IP socket.
Dim sender As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
' Connect the socket to the remote endpoint.
sender.Connect(remoteEP)
Console.WriteLine("Socket connected to {0}", _
sender.RemoteEndPoint.ToString())
' Encode the data string into a byte array.
Dim msg As Byte() = _
Encoding.ASCII.GetBytes("This is a test<EOF>")
' Send the data through the socket.
Dim bytesSent As Integer = sender.Send(msg)
' Receive the response from the remote device.
Dim bytesRec As Integer = sender.Receive(bytes)
Console.WriteLine("Echoed test = {0}", _
Encoding.ASCII.GetString(bytes, 0, bytesRec))
' Release the socket.
sender.Shutdown(SocketShutdown.Both)
sender.Close()
Console.ReadLine()
End Sub
End Class 'SynchronousSocketClient
But it does not work because of the PORT setting.
If in the TCP Server I have "Dim localEndPoint As New IPEndPoint(ipAddress, 0)" then the client crashes, but if I change the port from any (0) to 11000 for example, the client works fine.
Do you know why?
Later edit 2:
Maybe I should have started with this question: Which method is recommended for my scope - asynchronous or synchronous method?
Yes, you are on the right path.
The next thing to do is to introduce message detection since TCP is stream based and not message based like UDP. This means that TCP might decide to send two of your messages in the same packet (so that one socket.Recieve will get two messages) or that it will split up your message into two packets (thus requiring you to use two socket.Recieve to get it).
The two most common ways to create message detection is:
Create a fixed size header which includes message size
Create a delimiter which is appended to all messages.
Your "server" isn't listening on a set port, so you'll need to pay attention to the "You are listening on" message that appears. Then, from another machine on the network, telnet the.ip.add.ress port. (This may require installing "telnet client", or enabling it in the Programs and Features stuff, or whatever.)
Side note...if you actually intend for this to be a server of some sort, you'll want to decide what port you want to use, so that other computers can find your service. Most people won't be able to read your screen to figure out where to connect. :)
As for your "client"...when you connect to another computer, you don't just "pick a port" (which is what a port number of 0 means in an endpoint). You need to know what port the server uses. (Reread what i said in the previous paragraph. A program running on another computer has no idea what port to use to connect to the server -- any server could be running on any port.) You need to pick a port number for the server (say, 11000...good as any, really) rather than letting it use port 0.