您的位置:首页 > 理论基础 > 计算机网络

VB.NET中TCP通讯代码(客户端和接受端集成在一个窗口中)

2007-05-12 19:55 579 查看
      
        1、首先是界面的设置,界面设置系统会自动在Designer.vb这个文件中记录下来 ,下面是该文件的代码:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
       Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.TextBox1 = New System.Windows.Forms.TextBox
        Me.TextBox2 = New System.Windows.Forms.TextBox
        Me.BtnLink = New System.Windows.Forms.Button
        Me.BtnSend = New System.Windows.Forms.Button
        Me.LabService = New System.Windows.Forms.Label
        Me.ListBoxClientContext = New System.Windows.Forms.ListBox
        Me.StartService = New System.Windows.Forms.Button
        Me.StatusStrip1 = New System.Windows.Forms.StatusStrip
        Me.ToolStripLable1 = New System.Windows.Forms.ToolStripStatusLabel
        Me.ToolStripSeviceStatus = New System.Windows.Forms.ToolStripStatusLabel
        Me.StatusStrip1.SuspendLayout()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Location = New System.Drawing.Point(25, 22)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(77, 12)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "服务器地址:"
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.Location = New System.Drawing.Point(25, 69)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(41, 12)
        Me.Label2.TabIndex = 1
        Me.Label2.Text = "信息:"
        '
        'TextBox1
        '
        Me.TextBox1.Location = New System.Drawing.Point(115, 19)
        Me.TextBox1.Name = "TextBox1"
        Me.TextBox1.Size = New System.Drawing.Size(149, 21)
        Me.TextBox1.TabIndex = 2
        '
        'TextBox2
        '
        Me.TextBox2.Location = New System.Drawing.Point(115, 69)
        Me.TextBox2.Name = "TextBox2"
        Me.TextBox2.Size = New System.Drawing.Size(149, 21)
        Me.TextBox2.TabIndex = 3
        '
        'BtnLink
        '
        Me.BtnLink.Location = New System.Drawing.Point(27, 130)
        Me.BtnLink.Name = "BtnLink"
        Me.BtnLink.Size = New System.Drawing.Size(75, 23)
        Me.BtnLink.TabIndex = 4
        Me.BtnLink.Text = "连接"
        Me.BtnLink.UseVisualStyleBackColor = True
        '
        'BtnSend
        '
        Me.BtnSend.Location = New System.Drawing.Point(177, 129)
        Me.BtnSend.Name = "BtnSend"
        Me.BtnSend.Size = New System.Drawing.Size(75, 23)
        Me.BtnSend.TabIndex = 5
        Me.BtnSend.Text = "发送"
        Me.BtnSend.UseVisualStyleBackColor = True
        '
        'LabService
        '
        Me.LabService.AutoSize = True
        Me.LabService.Location = New System.Drawing.Point(25, 162)
        Me.LabService.Name = "LabService"
        Me.LabService.Size = New System.Drawing.Size(77, 12)
        Me.LabService.TabIndex = 0
        Me.LabService.Text = "服务尚未启动"
        '
        'ListBoxClientContext
        '
        Me.ListBoxClientContext.FormattingEnabled = True
        Me.ListBoxClientContext.ItemHeight = 12
        Me.ListBoxClientContext.Location = New System.Drawing.Point(27, 182)
        Me.ListBoxClientContext.Name = "ListBoxClientContext"
        Me.ListBoxClientContext.Size = New System.Drawing.Size(245, 148)
        Me.ListBoxClientContext.TabIndex = 1
        '
        'StartService
        '
        Me.StartService.Location = New System.Drawing.Point(27, 351)
        Me.StartService.Name = "StartService"
        Me.StartService.Size = New System.Drawing.Size(75, 23)
        Me.StartService.TabIndex = 2
        Me.StartService.Text = "启动服务"
        Me.StartService.UseVisualStyleBackColor = True
        '
        'StatusStrip1
        '
        Me.StatusStrip1.Items.AddRange(New System.Windows.Forms.ToolStripItem() {Me.ToolStripLable1, Me.ToolStripSeviceStatus})
        Me.StatusStrip1.Location = New System.Drawing.Point(0, 399)
        Me.StatusStrip1.Name = "StatusStrip1"
        Me.StatusStrip1.Size = New System.Drawing.Size(299, 22)
        Me.StatusStrip1.TabIndex = 6
        Me.StatusStrip1.Text = "StatusStrip1"
        '
        'ToolStripLable1
        '
        Me.ToolStripLable1.Name = "ToolStripLable1"
        Me.ToolStripLable1.Size = New System.Drawing.Size(55, 17)
        Me.ToolStripLable1.Text = "无连接!"
        '
        'ToolStripSeviceStatus
        '
        Me.ToolStripSeviceStatus.Name = "ToolStripSeviceStatus"
        Me.ToolStripSeviceStatus.Size = New System.Drawing.Size(91, 17)
        Me.ToolStripSeviceStatus.Text = "服务器无连接!"
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 12.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.ClientSize = New System.Drawing.Size(299, 421)
        Me.Controls.Add(Me.StatusStrip1)
        Me.Controls.Add(Me.BtnSend)
        Me.Controls.Add(Me.BtnLink)
        Me.Controls.Add(Me.TextBox2)
        Me.Controls.Add(Me.TextBox1)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.StartService)
        Me.Controls.Add(Me.ListBoxClientContext)
        Me.Controls.Add(Me.LabService)
        Me.Name = "Form1"
        Me.Text = "客户端"
        Me.StatusStrip1.ResumeLayout(False)
        Me.StatusStrip1.PerformLayout()
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
    Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
    Friend WithEvents BtnLink As System.Windows.Forms.Button
    Friend WithEvents BtnSend As System.Windows.Forms.Button
    Friend WithEvents LabService As System.Windows.Forms.Label
    Friend WithEvents ListBoxClientContext As System.Windows.Forms.ListBox
    Friend WithEvents StartService As System.Windows.Forms.Button
    Friend WithEvents StatusStrip1 As System.Windows.Forms.StatusStrip
    Friend WithEvents ToolStripLable1 As System.Windows.Forms.ToolStripStatusLabel
    Friend WithEvents ToolStripSeviceStatus As System.Windows.Forms.ToolStripStatusLabel

End Class
2、其次是类,即其控件所对应的方法,在这里注意的是,里面因为需要侦听端口号,所以需要新增一个线程,但是控件是不能跨线程使用的,需要用委托,代码如下:

Imports System.Net.Sockets
'使用到TcpListen类
Imports System.IO
'使用到StreamWriter类
Imports System.Net
'使用IPAddress类、IPHostEntry类等
Imports System.Threading

Public Class Form1

    'Client 端变量定义
    Private swWriter As StreamWriter
    '用以向网络基础数据流传送数据
    Private Client_nsStream As NetworkStream
    '创建发送数据的网络基础数据流
    Private tcpClient As System.Net.Sockets.TcpClient
    '通过它实现向远程主机提出TCP连接申请
    Private tcpConnect As Boolean = False
    '定义标识符,用以表示TCP连接是否建立

    'Server端变量定义
    Private iPort As Integer = 11000
    '定义侦听端口号
    Private thThreadRead As Thread
    '创建线程,用以侦听端口号,接收信息
    Private tlTcpListen As TcpListener
    '侦听端口号
    Private blistener As Boolean = True
    '设定标示位,判断侦听状态
    Private Service_nsStream As NetworkStream
    '创建接收的基本数据流
    Private srRead As StreamReader
    '从网络基础数据流中读取数据
    Private tcClient As TcpClient
    '用于确认客户端TCP连接请求

    Private Sub Listen()
        Try
            tlTcpListen = New TcpListener(iPort)
            '以8000端口号来初始化TcpListener实例
            tlTcpListen.Start()
            '开始监听
            Me.ToolStripSeviceStatus.Text = "正在监听..."
            tcClient = tlTcpListen.AcceptTcpClient()
            '通过TCP连接请求
            Service_nsStream = tcClient.GetStream()
            '获取用以发送、接收数据的网络基础数据流
            srRead = New StreamReader(Service_nsStream)
            '以得到的网络基础数据流来初始化StreamReader实例
            Me.ToolStripSeviceStatus.Text = "已经建立TCP连接!"
            '循环侦听
            While blistener
                Dim sMessage As String = srRead.ReadLine()
                '从网络基础数据流中读取一行数据
                If (sMessage = "STOP") Then
                    'Me.StartService.Enabled = True
                    Me.StartService.BeginInvoke(New System.EventHandler(AddressOf StartServiceUpdateUI))
                    tlTcpListen.Stop()
                    '关闭侦听
                    Service_nsStream.Close()
                    srRead.Close()
                    '释放资源
                    Me.ToolStripSeviceStatus.Text = "无连接!"
                    Me.LabService.BeginInvoke(New System.EventHandler(AddressOf LabServiceUpdateUI))
                    ' LabService.Text = "服务尚未启动!"
                    thThreadRead.Abort()
                    '中止线程
                    Me.StartService.Enabled = True

                    Return
                Else

                    Try
                        '判断是否为断开TCP连接控制码
                        Dim sTime As String = DateTime.Now.ToShortTimeString()
                        '获取接收数据时的时间
                        ListBoxClientContext.BeginInvoke(New System.EventHandler(AddressOf ListBoxUpdateUI), sTime + " " + sMessage)
                        '   ListBoxClientContext.Items.Add(sTime + " " + sMessage)
                    Catch ex As Exception
                        MessageBox.Show(ex.ToString())
                    End Try

                End If
            End While
        Catch ex As System.Security.SecurityException
            MessageBox.Show("侦听失败!", "错误")
        End Try
    End Sub

    Private Sub StartServiceUpdateUI(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.StartService.Enabled = True
    End Sub
    Private Sub LabServiceUpdateUI(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.LabService.Text = "服务尚未启动!"
    End Sub

    Private Sub ListBoxUpdateUI(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ListBoxClientContext.Items.Add(sender.ToString())
    End Sub

    Private Sub StartService_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartService.Click
        thThreadRead = New Thread(New ThreadStart(AddressOf Listen))
        '以Listen过程来初始化线程实例
        thThreadRead.Start()
        '启动线程
        StartService.Enabled = False
        LabService.Text = "服务已经启动!"
        LabService.ForeColor = Color.Red
    End Sub

    Private Sub BtnLink_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnLink.Click

        Dim ipRemote As IPAddress
        'Dim sHostName As String
        ' Dim tcpClient As TCPClient
        Try
            ipRemote = IPAddress.Parse(TextBox1.Text)
        Catch
            MessageBox.Show("输入的IP地址不合法!", "错误提示!")
            Return
            '判断给定的IP地址的合法性
        End Try
        Try
            tcpClient = New Sockets.TcpClient(TextBox1.Text, 11000)
            '对远程主机的8000端口提出TCP连接申请
            Client_nsStream = tcpClient.GetStream()
            '通过申请,并获取传送数据的网络基础数据流
            swWriter = New StreamWriter(Client_nsStream)
            '使用获取的网络基础数据流来初始化StreamWriter实例
            BtnLink.Enabled = False
            BtnSend.Enabled = True
            tcpConnect = True
            Me.ToolStripLable1.Text = "已经连接!"
        Catch
            MessageBox.Show("无法和远程主机11000端口建立连接!", "错误提示!")
            Return
        End Try

    End Sub

    Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
        If (TextBox2.Text <> "") Then
            swWriter.WriteLine(TextBox2.Text)

            If TextBox2.Text = "STOP" Then
                BtnLink.Enabled = True
                swWriter.Flush()
                '刷新当前数据流中的数据
                Client_nsStream.Close()
                swWriter.Close()
                '清除资源 ( )

            Else
                '刷新当前数据流中的数据
                swWriter.Flush()

            End If
            TextBox2.Text = ""

        Else
            MessageBox.Show("发送信息不能为空!", "错误提示!")
        End If
    End Sub
End Class
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐