Jump to content

[vb.net 2005]uma ligação com thread e udp


watt

Recommended Posts

boa tarde! Estou aqui com um problema que não estou a conseguir a dar a volta. eu fiz um cliente que envia um comando sql para um servidor e recebo a resposta... tudo ok. quando a resposta do servidor é um ele deveria de abrir um novo form, mas só que abre e fecha logo. será q alguem me pode ajudar ??? o cadigo fica kai em baixo.

Form do login Class


Imports System.Threading
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports System.Security.Cryptography

Public Class login

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Envia dados de login para o servidor
        Dim Md5 As New MD5CryptoServiceProvider
        Dim count As Int32 = 0

        Dim strPlainText As String = txtuser.Text
        Dim hashedDataBytes As Byte()
        Dim encoder As New UTF8Encoding()
        Dim md5Hasher As New MD5CryptoServiceProvider()
        hashedDataBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPlainText))
        Dim strHash As String = BitConverter.ToString(hashedDataBytes).Replace("-", "").ToLower


        clienteudp.Connect(ipserver, 3649)
        Dim sendBytes As Byte()
        sendBytes = Encoding.UTF8.GetBytes("Esql:Select count(*) from users where user like '" & txtuser.Text & "' and password Like '" & strHash & "'")
        clienteudp.Send(sendBytes, sendBytes.Length)
        clienteudp.Close()
        ThreadReceber = New System.Threading.Thread(AddressOf ReceberMsg)
        ThreadReceber.Start()
    End Sub

    Public Sub ReceberMsg()
        Try
            Dim x As String
            clienteudp = New UdpClient(3649)
            ipremoto = New IPEndPoint(IPAddress.Any, 0)
            receberbytes = clienteudp.Receive(ipremoto)
            dadosrecebidos = Encoding.UTF8.GetString(receberbytes)
            x = dadosrecebidos.ToString()
            MsgBox(x)

            If x = "1" Then
                ThreadReceber.Abort()
                clienteudp.Close()
                User = txtuser.Text
                Principal.Show()
                'Me.Close()
            End If
            thiniciar()
        Catch e As Exception
            MsgBox(e.Message, MsgBoxStyle.Critical, "ERRO")
            ThreadReceber.Abort()
            clienteudp.Close()
        End Try

    End Sub

    Public Sub thiniciar()
        ThreadReceber = New System.Threading.Thread(AddressOf ReceberMsg)
        ThreadReceber.Start()
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Me.Close()
    End Sub

    Private Sub login_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        clienteudp.Close()
    End Sub

Class das variaveis

Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Module variaveis
    'Transmitir e receber dados via UDP
    Public clienteudp As New UdpClient(3649)
    Public ipremoto As New IPEndPoint(IPAddress.Any, 0)
    Public receberbytes As Byte()
    Public dadosrecebidos As String
    Public ThreadReceber As Threading.Thread
    Public ipserver As String = "192.168.0.80"

    'Gerais
    Public User As String


End Module

Help-me, este thread e udp's nem me deixam dormir... :nono1:

Link to comment
Share on other sites

Não tenho grande experiencia com Threads... mas não será por tares a abrir o Form na thread que foi abortada? Tenta ver algo sobre Delegates relaccionado com Threads... acho que te ajuda em algo. Soz mas n te sei ajudar melhor, apenas usei threads numa situação e era bastante simples.

Se continuares sem resolver o teu problema, recorre aos forums da Microsoft ou aos newsgroups que lá tens mta gente que percebe do assunto a ajudar. (acredita que ja recorri a esses sitios e safaram-me bem)

Link to comment
Share on other sites

form modal?! é isto

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class login
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing AndAlso components IsNot Nothing Then
            components.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(login))
        Me.Button1 = New System.Windows.Forms.Button
        Me.txtuser = New System.Windows.Forms.TextBox
        Me.txtpass = New System.Windows.Forms.TextBox
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Button2 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(140, 245)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(79, 23)
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Entrar"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'txtuser
        '
        Me.txtuser.Location = New System.Drawing.Point(124, 193)
        Me.txtuser.Name = "txtuser"
        Me.txtuser.Size = New System.Drawing.Size(126, 20)
        Me.txtuser.TabIndex = 1
        '
        'txtpass
        '
        Me.txtpass.Location = New System.Drawing.Point(124, 219)
        Me.txtpass.Name = "txtpass"
        Me.txtpass.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
        Me.txtpass.Size = New System.Drawing.Size(126, 20)
        Me.txtpass.TabIndex = 2
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.BackColor = System.Drawing.Color.Transparent
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.ForeColor = System.Drawing.Color.Snow
        Me.Label1.Location = New System.Drawing.Point(41, 195)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(80, 18)
        Me.Label1.TabIndex = 3
        Me.Label1.Text = "Utilizador"
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.BackColor = System.Drawing.Color.Transparent
        Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 11.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.ForeColor = System.Drawing.Color.Snow
        Me.Label2.Location = New System.Drawing.Point(39, 221)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(83, 18)
        Me.Label2.TabIndex = 4
        Me.Label2.Text = "Password"
        '
        'Button2
        '
        Me.Button2.Location = New System.Drawing.Point(140, 274)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(79, 23)
        Me.Button2.TabIndex = 5
        Me.Button2.Text = "Sair"
        Me.Button2.UseVisualStyleBackColor = True
        '
        'login
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackgroundImage = CType(resources.GetObject("$this.BackgroundImage"), System.Drawing.Image)
        Me.ClientSize = New System.Drawing.Size(292, 354)
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.txtpass)
        Me.Controls.Add(Me.txtuser)
        Me.Controls.Add(Me.Button1)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        Me.Name = "login"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Form1"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents txtuser As System.Windows.Forms.TextBox
    Friend WithEvents txtpass As System.Windows.Forms.TextBox
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Button2 As System.Windows.Forms.Button

End Class

calculas o que seja ?!

Link to comment
Share on other sites

Nao isto :

    If x = "1" Then

                ThreadReceber.Abort()

                clienteudp.Close()

                User = txtuser.Text

                Principal.ShowDialog

                'Me.Close()

            End If

"The Dark Side Clouds Everthing. Impossible To See The Future Is."My rig: Intel Core 2 Quad Q9450 | abit IP35P | 4G Kingston 800 Mhz | XFX GeForce 9800 GX2 1G ddr3 | 2X WD5000AAJS 500Gb Sata 2 | PSU 600W || Caixa El-Diablo | Creative XMod

Link to comment
Share on other sites

Nao isto :

    If x = "1" Then

                ThreadReceber.Abort()

                clienteudp.Close()

                User = txtuser.Text

                Principal.ShowDialog

                'Me.Close()

            End If

meto isso e quase q corre td bem, mas depois não consigo enviar as variaveis, e quando tiro  ' do me.close dá erro, e aqui tb dá erro  ThreadReceber.Abort()

diz sp:

Cross-thread operation not valid: Control 'login' accessed from a thread other than the thread it was created on.

Link to comment
Share on other sites

Bem, vamos la ajudar o rapaz...

Como eu disse no post anterior, disse para meter um ciclo infinito, que provalmente nao o fizeste...

Delegate Sub Data(ByVal Data As String)

Dim DelData as Data(AddressOf ProcessData)

Public Sub ProcessData(Data as string)

    Textbox1.Text = Data

End Sub

Na Thread no local onde queres passar o valor, tiras a linha e metes Invoke(DelData, variavel)

Se tiveres algum problema diz  :smoke:

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.