vb.net

vb.net UDP傳送接收聊天室

下面為傳送端
Imports System.Net         '網路基礎功能相關函數

Imports System.Net.Sockets '網路連線功能相關函數

Imports System.Text        '文字編碼功能相關函數 

Public Class Form_send

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        Dim C As New UdpClient

        Dim EP As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 2017) '應為目標程式所在之IP

        C.Connect(EP)

        Dim B() As Byte = Encoding.Default.GetBytes(TextBox1.Text)

        C.Send(B, B.Length)

        Dim R() As Byte = C.Receive(EP)

        TextBox2.Text = TextBox2.Text + Encoding.Default.GetString(R)

    End Sub

End Class

下面為接收端

Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Threading

Public Class Form_receive

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        '建立執行緒,執行 run 函式

        Dim t As Threading.Tasks.Task = Threading.Tasks.Task.Factory.StartNew(AddressOf run)
    End Sub


    Sub run()

        '更新 UI
        SetUI("執行緒開始", TextBox1)

        '   SetUI("執行緒結束", TextBox1)
        Dim U As New UdpClient(2017)
        Dim A As String
        Do While True

            Dim EP As New IPEndPoint(IPAddress.Any, 2017) '建立監聽端點資訊

            Dim B() As Byte = U.Receive(EP)

            A = Encoding.Default.GetString(B) '翻譯資訊為字串
            '更新 UI
            SetUI(A, TextBox1)
            Dim M As String = "Unknown Command"

            If A = "Time?" Then

                M = Now.ToString + "asd"

            End If

            B = Encoding.Default.GetBytes(M)

            U.Send(B, B.Length, EP) '回應詢問資料

        Loop
        ' raise一個事件出來說已經做完了
        ' 並將處理完的值回傳回去
    End Sub


    '設定 UI 

    Private Delegate Sub UpdateUI(ByVal msg As String, ByVal con As Control)

    Sub SetUI(ByVal str As String, ByVal con As Control)

        If Me.InvokeRequired() Then
            Dim um As New UpdateUI(AddressOf SetUI)
            Me.Invoke(um, str, con)
        Else
            TextBox1.Text = str
        End If

    End Sub


End Class



Be the First to comment.

Leave a Comment

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

(若看不到驗證碼,請重新整理網頁。)