VB服务端通讯代码174
发表时间:2018-04-09 11:35 Imports System.Net.Sockets '使用到TcpListen类 Imports System.Threading '使用到线程 Imports System.IO '使用到StreamReader类 Imports System.Net Public Class Form1 Private iPort As Integer = 8000 '定义侦听端口号 Private thThreadRead As Thread '创建线程,用以侦听端口号,接收信息 Private tlTcpListen As TcpListener '侦听端口号 Private blistener As Boolean = True '设定标示位,判断侦听状态 Private nsStream As NetworkStream '创建接收的基本数据流 Private srRead As StreamReader '从网络基础数据流中读取数据 Private tcClient As TcpClient Private Sub Listen() Try Dim localAddr As IPAddress = IPAddress.Parse("127.0.0.1") tlTcpListen = New TcpListener(localAddr, iPort) '以8000端口号来初始化TcpListener实例 tlTcpListen.Start() '开始监听 StatusBar1.Text = "正在监听..." tcClient = tlTcpListen.AcceptTcpClient() '通过TCP连接请求 nsStream = tcClient.GetStream() '获取用以发送、接收数据的网络基础数据流 srRead = New StreamReader(nsStream) '以得到的网络基础数据流来初始化StreamReader实例 StatusBar1.Text = "已经建立TCP连接!" '循环侦听 While blistener Dim sMessage As String = srRead.ReadLine() '从网络基础数据流中读取一行数据 If (sMessage = "STOP") Then tlTcpListen.Stop() '关闭侦听 nsStream.Close() srRead.Close() '释放资源 StatusBar1.Text = "无连接!" thThreadRead.Abort() '中止线程 Return Else '判断是否为断开TCP连接控制码 Dim sTime As String = DateTime.Now.ToLongTimeString() '获取接收数据时的时间 SetText(sTime + " " + sMessage) End If End While Catch ex As System.Security.SecurityException MessageBox.Show("侦听失败!", "错误") End Try End Sub Private Sub SetText(ByVal [text] As String) ' InvokeRequired required compares the thread ID of the' calling thread to the ' thread ID of the creating thread.' If these threads are different, it returns true. If Me.ListBox1.InvokeRequired Then Dim d As New ContextCallback(AddressOf SetText) Me.Invoke(d, New Object() {[text]}) Else Me.ListBox1.Items.Add([text]) End If End Sub Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click thThreadRead = New Thread(New ThreadStart(AddressOf Listen)) '以Listen过程来初始化线程实例 thThreadRead.Start() '启动线程 Button1.Enabled = False Label1.Text = "服务已经启动!" Label1.ForeColor = Color.Red End Sub Private Sub Form1_Disposed(sender As Object, e As System.EventArgs) Handles Me.Disposed Try thThreadRead.Abort() '中止线程 tlTcpListen.Stop() '关闭侦听 tcClient.Close() nsStream.Close() srRead.Close() '释放资源 Catch End Try If Disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(Disposing) End Sub End Class |