这里写的是上位机基本的程序,有什么额外功能的话可以自己加上。我是参与别人项目里做的,主要实现了自动检测,断点重连,发送检测消息。因为要实时使用,所以要最大程度的避免程序崩溃,因此程序里使用了比较多的try模块。同是为了让别人使用起来方便,没有做其他修饰的东西。
Public Class Form1
//用到的全局变量
Public socketi As Net.Sockets.Socket'套接字
Dim funct As String
Dim funct1 As String = "Speed_LocPIDInit"
Dim funct2 As String = "Angle_LocPIDInit"
Dim Aip As String'该客户端ip
Dim Aport As String'该客户端port
Dim fg As Boolean = True'它的值表示连接是否正常
Dim reg As Boolean = True
Dim Acc As Timers.Timer '接受服务器信息的定时器
Dim Isone As Boolean = True
Dim Lock_syn As New Object()'线程锁
Dim Send_Timer As Timers.Timer'定时发送消息的定时器
Dim end_start As Boolean
'///////////////////////////
'按下左上角的X是调用该过程,关闭定时器,套接字等。
Public Sub Ending()
Try
socketi.Close()
Catch ce As Exception
End Try
Try
Ch.Abort()
Catch ex As Exception
End Try
Try
' Th.Abort()
Acc.Stop()
Catch ex As Exception
End Try
Try
Send_Timer.Stop()
Catch ex As Exception
End Try
fg = True
End Sub
'////////////////////////////////
'定时发送所调用的过程
Public Sub Time_Send()
Dim str As String = "test" & Now().ToString()'当前的时间
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(str)
Try
socketi.Send(btText)
Catch ie As Exception
End Try
End Sub
'/////////////////////////////
'自动检测连接是否断开,如果断开,则一直尝试重连并且每次重连会显示出来
Public Sub Ch_fun()
Dim str As Int32 = 1
Dim cf As Int32 = 1
While 1
Threading.Thread.Sleep(80)
If fg = False Then
' 10035 == WSAEWOULDBLOCK
socketi.Close()
Button1.Enabled = True
Button2.Enabled = False
Label11.Text = "连接断开,正在重连"
Dim LocalEndPoint As New Net.IPEndPoint(Net.IPAddress.Parse(Aip), CInt(Aport))
Dim client As Net.Sockets.Socket = Nothing
client = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
'尝试重连
While 1
Try
Label11.Text = "第" & str.ToString() & "次重连"
str = str + 1
client.Connect(LocalEndPoint)
socketi = client
Dim tmp(0) As Byte
socketi.Blocking = False
socketi.Send(tmp, 0, 0)
Label11.Text = "连接正常"
socketi.Blocking = True
Button2.Enabled = True
str = 1
fg = True
Exit While
Catch ex As Exception
Label11.Text = "连接断开,正在重连"
Threading.Thread.Sleep(1000)
Continue While
End Try
End While
Else
Label11.Text = "连接正常"
cf = cf + 1
TextBox10.Text = cf.ToString()
End If
End While
End Sub
'////////////////////////////////////
'接收消息所用的过程
Public Sub Task()
If fg = False Then
Exit Sub
End If
Acc.Enabled = False'接受消息可能会堵塞,设置该值是为了防止重复触发
Dim str As New Text.StringBuilder
Dim str2 As String = Nothing
Dim str3 As String = Nothing
Dim by(100) As Byte
Dim ch(100) As Char
Dim ch1(100) As Char
Dim err As Int32
Try
err = socketi.Receive(by)
Catch e As Exception'err<0说明连接出问题
fg = False
Acc.Enabled = True
Exit Sub
End Try
If err > 0 Then
str.Append(System.Text.ASCIIEncoding.ASCII.GetString(by, 0, by.Length()))
'////////////////////////////////
Dim str1 As String = str.ToString()
TextBox4.AppendText(vbNewLine & str1)
TextBox4.ScrollToCaret()
ElseIf err <= 0 Then
fg = False
Acc.Enabled = True
Exit Sub
End If
Acc.Enabled = True
End Sub
'//////////////////////////////
'连接过程
Public Sub connecting()
Ending()'启动新连接前把上个连接关闭。
fg = True
Dim flag As Int32 = 1
Dim Ip As String = Nothing
Dim Port As String = Nothing
Ip = TextBox1.Text
Aip = Ip
While Ip Is ""
MsgBox("请输入Ip地址", MsgBoxStyle.OkOnly, Me.Text)
Return
End While
Port = TextBox2.Text
Aport = Port
While Port Is ""
MsgBox("请输入Port地址", MsgBoxStyle.OkOnly, Me.Text)
Return
End While
'///////////////////////////////////////////////////////////链接代码
Dim LocalEndPoint As New Net.IPEndPoint(Net.IPAddress.Parse(Ip), CInt(Port))
Dim client As Net.Sockets.Socket = Nothing
client = New Net.Sockets.Socket(Net.Sockets.AddressFamily.InterNetwork, Net.Sockets.SocketType.Stream, Net.Sockets.ProtocolType.Tcp)
' This is how you can determine whether a socket is still connected.
Dim blockingState As Boolean = client.Blocking
Try
client.Connect(LocalEndPoint)
socketi = client
Dim tmp(0) As Byte
client.Blocking = True
client.Send(tmp, 0, 0)
MsgBox("Connected!")
Catch ie As Exception
' 10035 == WSAEWOULDBLOCK
MsgBox("connet failed!, please check your Ip, Port", MsgBoxStyle.Exclamation)
Button1.Enabled = True
Return
Finally
client.Blocking = blockingState
End Try
'end_start = False
client.Blocking = True
'MsgBox("Connected: {0}", client.Connected)
If flag <> 1 Then
Return
End If
'初始化Ch,Acc
Ch = New Threading.Thread(AddressOf Ch_fun)
Ch.Start()
Acc = New Timers.Timer(80)
Send_Timer = New Timers.Timer(FormatNumber(TextBox11.Text()))
AddHandler Acc.Elapsed, AddressOf Task
Acc.Start()
AddHandler Send_Timer.Elapsed, AddressOf Time_Send
Send_Timer.Start()
End Sub
'//////////////////////
'开始时设置默认参数
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "127.0.0.1"
TextBox2.Text = "8888"
TextBox8.Text = "8"
TextBox5.Text = "2"
TextBox6.Text = "60"
TextBox7.Text = "18"
TextBox9.Text = "5"
TextBox11.Text = "500"
connecting()
End Sub
'////////////////
'连接按钮触发事件
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Label11.Text = ""
connecting()
End Sub
'///////////////////////////
'发送按钮
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim str As String = Nothing
str = TextBox3.Text
If str Is "" Then
MsgBox("请输入数据", MsgBoxStyle.Information)
Return
End If
'////////////////////////////////////////
'下面注释的程序是为了获取服务器返回的参数,可以忽略。
Dim fun(40) As Char
'Dim can1(20) As Char
'Dim can2(20) As Char
'Dim can3(20) As Char
'Dim i As Int32 = 0, j As Int32 = 0
'Dim size As Int32 = str.Length
'While i < size
' If str.Chars(i) = "("c Then
' Exit While
' End If
' fun(j) = str.Chars(i)
' j = j + 1
' i = i + 1
'End While
'i = i + 1
'j = 0
'While i < size
' If str.Chars(i) = ","c Then
' Exit While
' End If
' can1(j) = str.Chars(i)
' j = j + 1
' i = i + 1
'End While
'i = i + 1
'j = 0
'While i < size
' If str.Chars(i) = ","c Or str.Chars(i) = ")"c Then
' Exit While
' End If
' can2(j) = str.Chars(i)
' j = j + 1
' i = i + 1
'End While
'i = i + 1
'j = 0
'While i < size
' If str.Chars(i) = ","c Or str.Chars(i) = ")"c Then
' Exit While
' End If
' can3(j) = str.Chars(i)
' j = j + 1
' i = i + 1
'End While
If socketi.Connected = False Then
Return
End If
Dim str1 As String = TextBox4.Text
If str1 <> "" Then
TextBox4.AppendText(vbNewLine & str & vbNewLine)
Else
TextBox4.AppendText(str & vbNewLine)
End If
TextBox4.ScrollToCaret()
End Sub
'///////////////
'断开按钮
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Try
socketi.Close()
Catch be As Exception
End Try
Try
Ch.Abort()
Catch ex As Exception
End Try
Try
' Th.Abort()
Acc.Stop()
Catch ex As Exception
End Try
Try
'
Send_Timer.Stop()
Catch ex As Exception
End Try
MsgBox("连接断开")
reg = True
Button1.Enabled = True
Button2.Enabled = True
Label11.Text = "状态"
SyncLock Lock_syn
Isone = True
End SyncLock
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim str1 As String = funct1
Dim str2 As String = TextBox8.Text
Dim str3 As String = TextBox5.Text
Dim str4 As String = TextBox6.Text
Dim str5 As String
str5 = str1 & "(" & str2 & "," & str3 & "," & str4 & ")" & vbNewLine
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(str5)
socketi.Send(btText)
Dim s As String = TextBox4.Text
TextBox4.AppendText(vbNewLine & str5 & vbNewLine)
TextBox4.ScrollToCaret()
End Sub
Private Sub TextBox8_TextChanged(sender As Object, e As EventArgs) Handles TextBox8.TextChanged
End Sub
Private Sub Label4_Click_1(sender As Object, e As EventArgs) Handles Label4.Click
End Sub
Private Sub TextBox6_TextChanged(sender As Object, e As EventArgs) Handles TextBox6.TextChanged
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim str1 As String = funct2
Dim str2 As String = TextBox7.Text
Dim str3 As String = TextBox9.Text
Dim str5 As String
str5 = str1 & "(" & str2 & "," & str3 & ")" & vbNewLine
Dim encText As New System.Text.UTF8Encoding()
Dim btText() As Byte
btText = encText.GetBytes(str5)
socketi.Send(btText)
Dim s As String = TextBox4.Text
TextBox4.AppendText(vbNewLine & str5 & vbNewLine)
TextBox4.ScrollToCaret()
End Sub
'///////////////
'界面关闭时触发
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
Ending()
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Try
Send_Timer.Stop()
Catch ie As Exception
End Try
End Sub
源代码地址:https://github.com/fengasdf/WindowsApplication2