VB.NET中的TCP/IP通信 [英] TCP/IP communication in VB.NET
本文介绍了VB.NET中的TCP/IP通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的代码有一个小问题,我的整个程序在发送/接收TCP/IP消息时暂停.我还注意到,它会影响连接到相同IP地址但在不同端口上的另一个应用程序.我在这里处理错误吗?我假设一个事实,就是在我将消息发送到套接字后,我正在请求结果.我是否使用接收事件或类似事件?
任何建议将不胜感激.
提前谢谢!
这是我的代码:
Hi,
I have a slight problem with my code where my entire program halts while sending/receiving TCP/IP messages. I also noticed that it affects another application that is connected to the same IP address but on a different port. Am I handling something wrong here? I''m assuming the fact that right after I send the message to the socket I''m asking for the result. Do I use a receive event or something like that?
Any suggestions would be greatly appreciated.
Thanks in advance!
Here is my Code:
' MatchPort b/g RSSI Query over Telnet protocol
' Developed by Marco van der Merwe
' 23/08/2012
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Public Class MatchPortRSSI
Private TelnetSocket As Socket
Private MatchPortSSID As String
Private WithEvents tmrRSSI As New Timer
Public Event RSSI(ByVal dBmRx As Integer)
Private Sub TelnetRead()
Dim nRxBytes As Integer = 0
Dim RxBytes(100) As [Byte]
If TelnetSocket.Connected Then
nRxBytes = TelnetSocket.Receive(RxBytes, RxBytes.Length, 0)
Dim TelnetString As String = String.Empty
Dim i As Integer
If nRxBytes < 100 Then
For i = 0 To nRxBytes ' Filter out problematic characters
Select Case RxBytes(i)
Case 0
Case 1
Case 3
Case 10
TelnetString = TelnetString & vbNewLine
Case 13
TelnetString = TelnetString & vbNewLine
Case 251
Case 255
Case Else
TelnetString = TelnetString & Chr(RxBytes(i))
End Select
Next
End If
Dim intdBmIndex As Integer = TelnetString.IndexOf("dBm")
If intdBmIndex > 3 Then
Dim strRSSIval As String = TelnetString.Substring(intdBmIndex - 4, 3)
RaiseEvent RSSI(CInt(strRSSIval))
End If
End If
End Sub
Public Sub StartRSSI(ByVal strIPAddress As String, ByVal strSSID As String)
Dim MatchPortIPAddress As IPAddress = IPAddress.Parse(strIPAddress.Trim)
Dim TelnetServer As IPEndPoint = New IPEndPoint(MatchPortIPAddress, 9999)
TelnetSocket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
MatchPortSSID = strSSID
Try
TelnetSocket.Connect(TelnetServer)
Catch oEX As SocketException
' Error Handler
' Need to place code to deal with errors.
Exit Sub
End Try
If TelnetSocket.Connected Then
TelnetRead()
Dim strTx As String = "M" ' Places telnet into Monitor Mode
TelnetSocket.Send(Encoding.ASCII.GetBytes(strTx), strTx.Length, SocketFlags.None)
TelnetRead()
tmrRSSI.Enabled = True
End If
End Sub
Public Sub StopRSSI()
tmrRSSI.Enabled = False ' Stop timed RSSI Query
If TelnetSocket.Connected Then ' If connected close Telnet Monitor Mode
Dim strTx As String = "QU" & vbLf
TelnetSocket.Send(Encoding.ASCII.GetBytes(strTx), strTx.Length, SocketFlags.None)
TelnetSocket.Disconnect(False) ' Close TCP Port
End If
End Sub
Public Property Interval() As Integer
Get
Interval = tmrRSSI.Interval
End Get
Set(ByVal Interval As Integer)
tmrRSSI.Interval = Interval
End Set
End Property
Private Sub tmrRSSI_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrRSSI.Tick
If TelnetSocket.Connected Then
Dim strTx As String = "SA " & MatchPortSSID & vbLf
TelnetSocket.Send(Encoding.ASCII.GetBytes(strTx), strTx.Length, SocketFlags.None)
TelnetRead()
End If
End Sub
End Class
推荐答案
请参阅我对这个问题的评论-这是您需要做的主要部分.抱歉,在您完成部分工作之前,我不想花时间进行调查,但是我只能分享这段代码中的错误,乍一看就可以发现.
我可以看到的最大问题是您的try-catch块,其中包含SocketException
的捕获.仅在您完全了解某个特定catch块中发生的情况时,您才做一些很少做的事情,这是排除在外:您阻止异常的传播.不要做这是对异常的滥用.异常不应在所有可能出现的地方都被捕获;主要规则是:放手.该机制旨在将异常处理与常规"代码隔离开.我在对上述问题的评论中告诉您该怎么做.就您而言,只需完全删除try-catch.您现在拥有的只是使异常保持沉默,因此这就是为什么您不知道到底发生了什么的原因.
现在,过滤掉有问题的字符"至少是很奇怪的.请检查一下.
一般来说,您的问题是使用"魔法常数",更糟糕的是,立即常数.为什么在地球上是3、251或255,"M","QU","SA"?看你的"100".它重复了两次.如果您决定更改它,您将很容易忘记另一个地方,并把事情搞砸了.更好的情况是,至少要使用关键字const
显式声明所有常量,这样您就不必重复它们,并且在需要时可以使用它们对代码进行参数化.
另外,这些CodeProject文章可能对您有用,请参阅:
快速工具:简约的Telnet库 [ TelnetSocket [ ^ ],
Windows Mobile Telnet客户端 [
Please see my comment to the question — this is the main part of what you need to do. Sorry, I don''t want to spend time on investigation before you do you part of work, but I can only share what''s wrong in this code, what I can see from the first glance.
The biggest problem I can see is your try-catch block, with the catch forSocketException
. You are doing something which should be done very rarely, as an exclusion, and only if you know exactly what''s going on in some particular catch block: you block the propagation of the exception. Don''t do it; this is a misuse of exceptions. Exceptions should not be caught in every place then can appear; the main rule is: let go. The mechanism is designed to isolate exception handling from "regular" code. I told you what to do in my comment to the question above. In your case, just remove try-catch completely. What you have now simply makes the exception silent, so that''s why you don''t know what exactly happened.
Now, "filter out problematic characters" is at least weird. Please review it.
More generally, your problem is using "magical constants", worse, immediate constants. Why, on Earth, 3, 251 or 255, "M", "QU", "SA"?! Look at your "100". It it repeated twice. If you decide to change it, you will easily forget another place and screw up things heavily. Better, as a minimum, declare all constants explicitly, with the keywordconst
, this way you won''t repeat them and will be able to parametrize the code with them when you find it necessary.
Also, these CodeProject articles could be useful for you, please see:
Quick tool : A minimalistic Telnet library[^],
TelnetSocket[^],
Windows Mobile Telnet Client[^].
Good luck,
—SA
这篇关于VB.NET中的TCP/IP通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文