none
thread & socket RRS feed

  • 問題

  •  

     

    主程式按下按鈕後,開始等待client連線

     

    在client顯示已發送後(確定已送到server)

     

    主程式這邊收不到東西,encoding不出來任何資料

     

    不懂是不是使用thread的關係,所以資料沒辦法顯示在主視窗

     

    Code Snippet

    Public Class main

    Public serversocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)

    ...

        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Try
                Dim addlist As IPHostEntry
                addlist = Dns.GetHostEntry("localhost")
                Dim serverIP As IPAddress = addlist.AddressList(0)
                Dim serverhost As New IPEndPoint(serverIP, 77)
                serversocket.Bind(serverhost)
                serversocket.Listen(10)
                Dim lc As New listenclient(serversocket)
                lc.spinup()
            Catch ex As Exception
                content.AppendText(ex.ToString)
            End Try
        End Sub
    End Class

     

     

     

    Code Snippet

    Public Class listenclient


        Private serversocket As System.Net.Sockets.Socket
        Private clientsocket As System.Net.Sockets.Socket
        Private _thread As Thread
        Public s As String

     

        Public Sub New(ByVal serversocket As Socket)
            Me.serversocket = serversocket
            main.content.AppendText("已產生新執行緒")
        End Sub

     

        Public Sub spinup()
            main.content.AppendText("執行緒開始啟動" & vbCrLf)

            Dim threadstart As ThreadStart
            threadstart = New ThreadStart(AddressOf Me.serverthreadproc)
            _thread = New Thread(threadstart)
            _thread.Start()
        End Sub

     

        Public Sub serverthreadproc()

            Do While True
                Try

                    Dim clientsocket As Socket = serversocket.Accept()

                    Dim bytes(1024) As Byte

                    clientsocket.Receive(bytes, 0, clientsocket.Available, SocketFlags.None)
                    s = Encoding.ASCII.GetString(bytes)
                    clientsocket.Shutdown(SocketShutdown.Both)
                    clientsocket.Close()
                    main.content.AppendText(s)
                Catch ex As Exception
                    main.content.AppendText(ex.StackTrace.ToString())
                End Try
            Loop

        End Sub


    End Class

     

     

    可以請大家幫幫忙嗎,還想請問主程式的socket關閉程式該寫在哪??
    2008年11月30日 上午 11:01