Socket non connesso e indirizzo non fornito durante l'invio

di il
3 risposte

Socket non connesso e indirizzo non fornito durante l'invio

Buonasera, sto lavorando ad un programma chiamato che ho chiamato Multiplex; il software si offre di offrire la possibilità agli utenti di scaricare software inerenti alla sicurezza, giochi, algoritmi e matematica. Il programma non è ancora terminato, proprio adesso ho terminato di "gestire la disconnessione" sia del client che del server e visualizzo l'errore Socket non connesso e indirizzo non fornito durante l'invio su un socket di datagramma che utilizza una chiamata sendto. Richiesta di invio o ricezione di dati annullata alla riga
 Server.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), Server)
Vi posto sia il client che il server.

Client
Imports System.Net
Imports System.Net.Sockets

Public Class frmMain

    Dim ClientSock As Socket
    Dim ClientCount As Integer = 0
    Dim Data(1024) As Byte
    Dim Connected As Boolean = False

    Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        pbConnected.Hide()
        pbDisconnected.Hide()
    End Sub

    Private Sub btnConnect_Click_1(sender As System.Object, e As System.EventArgs) Handles btnConnect.Click
        If Connected Then
            btnConnect.Enabled = False
        Else
            ClientSock = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim IPAddr As IPAddress = IPAddress.Parse("127.0.0.1")
            Dim IPEndPnt As IPEndPoint = New IPEndPoint(IPAddr, 8800)
            ClientSock.BeginConnect(IPEndPnt, New AsyncCallback(AddressOf OnConnect), Nothing)
            Connected = True
            ClientCount += 1
            pbConnected.Show()
            pbDisconnected.Hide()
        End If
    End Sub

    Private Sub OnConnect(ByVal Result As IAsyncResult)
        ClientSock.EndConnect(Result)
        ClientSock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), ClientSock)
    End Sub

    Private Sub OnRecieve(ByVal Result As IAsyncResult)
        Dim Client As Socket = Result.AsyncState
        Client.EndReceive(Result)
        Dim Received As Byte() = Data
        Dim Message As String = System.Text.ASCIIEncoding.ASCII.GetString(Received)
        Read(Message)
        Client.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), ClientSock)
    End Sub

    Delegate Sub ReadMessage(ByVal Message As String)
    Private Sub Read(ByVal Message As String)
        If InvokeRequired Then
            Invoke(New ReadMessage(AddressOf Read), Message)
            Exit Sub
        End If
        If Message = "close" & ClientCount Then
            ClientSock.Close()
            pbConnected.Hide()
            pbDisconnected.Show()
        Else
            txtText.Text &= Message
        End If
    End Sub

    Private Sub frmMain_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If Connected Then
            Dim CloseBytesData() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("close" & ClientCount)
            ClientSock.BeginSend(CloseBytesData, 0, CloseBytesData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSendCloseBytesData), Nothing)
            ClientSock.Close()
            pbConnected.Hide()
            pbDisconnected.Show()
        Else
            Application.Exit()
        End If
    End Sub

    Private Sub OnSendCloseBytesData(ByVal Result As IAsyncResult)
        Dim client As Socket = Result.AsyncState
        client.EndSend(Result)
        ClientCount = 0
    End Sub

    Private Sub btnDisconnect_Click(sender As System.Object, e As System.EventArgs) Handles btnDisconnect.Click
        Dim CloseBytesData() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("close" & ClientCount)
        ClientSock.BeginSend(CloseBytesData, 0, CloseBytesData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSendCloseBytesData), Nothing)
        ClientSock.Close()
        pbConnected.Hide()
        pbDisconnected.Show()
    End Sub

    Private Sub ButtonExit_Click(sender As System.Object, e As System.EventArgs) Handles ButtonExit.Click
        Application.Exit()
    End Sub

    Private Sub MinimizeButton_Click(sender As System.Object, e As System.EventArgs) Handles MinimizeButton.Click
        Me.WindowState = FormWindowState.Minimized
    End Sub

End Class
Server
Imports System.Net
Imports System.Net.Sockets

Public Class frmMain
    Dim Server As Socket
    Dim ClientCount As Integer = 0
    Dim ClientSock As Socket
    Dim Data(1024) As Byte

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Server = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        Dim IpEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 8800)
        Server.Bind(IpEndPoint)
        Server.Listen(50)
        Server.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
    End Sub

    Private Sub OnAccept(ByVal Result As IAsyncResult)
        ClientSock = Server.EndAccept(Result)
        Server.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
        NewClient(ClientSock)
        ClientCount += 1
        Server.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), Server)
    End Sub

    Private Sub OnRecieve(ByVal Result As IAsyncResult)
        Dim Client As Socket = Result.AsyncState
        Client.EndReceive(Result)
        Dim Received As Byte() = Data
        Dim Message As String = System.Text.ASCIIEncoding.ASCII.GetString(Received)
        Read(Message)
        Client.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), Client)
    End Sub

    Delegate Sub ReadMessage(ByVal Message As String)
    Private Sub Read(ByVal Message As String)
        If InvokeRequired Then
            Invoke(New ReadMessage(AddressOf Read), Message)
            Exit Sub
        End If
        If Message = "close" & ClientCount Then
            lvClient.Items.RemoveAt(ClientCount - 1)
            Server.Close()
        Else
            Server.BeginAccept(New AsyncCallback(AddressOf OnAccept), Nothing)
        End If
    End Sub

    Delegate Sub AddNewClient(ByVal NewClient As Socket)
    Private Sub NewClient(ByVal Client As Socket)
        If InvokeRequired Then
            Invoke(New AddNewClient(AddressOf NewClient), Client)
            Exit Sub
        End If
        Dim ClientItem As New ListViewItem(Client.LocalEndPoint.ToString)
        ClientItem.Tag = Client
        lvClient.Items.Add(ClientItem)
    End Sub

    Private Sub SendMessageTo(ByVal Message As String, ByVal WichClient As Socket)
        Dim Bytes As Byte() = System.Text.ASCIIEncoding.ASCII.GetBytes(Message)
        WichClient.BeginSend(Bytes, 0, Bytes.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSend), WichClient)
    End Sub

    Private Sub OnSend(ByVal Result As IAsyncResult)
        Dim client As Socket = Result.AsyncState
        client.EndSend(Result)
    End Sub

    Private Sub MenuSendMessage_Click(sender As System.Object, e As System.EventArgs) Handles SendMessage.Click
        For Each SingleClient As Object In lvClient.SelectedItems(0).Tag
            If SingleClient.Connected Then
                SendMessageTo("Message from server", lvClient.SelectedItems(0).Tag)
            Else
                MessageBox.Show("Can't send messate to this client because it's not connected", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End If
        Next
    End Sub

    Private Sub frmMain_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        Dim CloseBytesData() As Byte = System.Text.ASCIIEncoding.ASCII.GetBytes("close")
        For Each SingleClient As Socket In lvClient.Items
            SingleClient.BeginSend(CloseBytesData, 0, CloseBytesData.Length, SocketFlags.None, New AsyncCallback(AddressOf OnSendCloseBytesData), Nothing)
            SingleClient.Close()
        Next
        lvClient.Clear()
    End Sub

    Private Sub OnSendCloseBytesData(ByVal Result As IAsyncResult)
        Dim client As Socket = Result.AsyncState
        client.EndSend(Result)
    End Sub

    Private Sub ButtonExit_Click(sender As System.Object, e As System.EventArgs) Handles ButtonExit.Click
        Application.Exit()
    End Sub

    Private Sub ButtonMinimize_Click(sender As System.Object, e As System.EventArgs) Handles ButtonMinimize.Click
        Me.WindowState = FormWindowState.Minimized
    End Sub

End Class

3 Risposte

  • Re: Socket non connesso e indirizzo non fornito durante l'invio

    Ho risolto il problema, cercando meglio su google ho trovato la risposta di Stephen Cleary qui : http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/a041f281-2174-4c1b-a172-c5527d3002a2/

    Praticamente ho sostituito questa riga
    Server.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), Server)
    con questa
    ClientSock.BeginReceive(Data, 0, Data.Length, SocketFlags.None, New AsyncCallback(AddressOf OnRecieve), Server)

    però non capisco perché se clicco su "Disconnetti" dal Client ( che dovrebbe disconnettere il client e inviando "close" + il relativo numero del client connesso ) si chiude sia il server che il client...tra l'altro se provo sia il client che il server senza debugger mi dice che entrambi hanno smesso di funzionare...
  • Re: Socket non connesso e indirizzo non fornito durante l'invio

    Ciao,
    prima di tutto grazie per aver condiviso la tua esperienza.
    Non è che il metodo Close chiude anche la parte server?
    Hai provato questo esempio Qui trovi la guida.
    Ciao e buona programmazione.
  • Re: Socket non connesso e indirizzo non fornito durante l'invio

    lele2006 ha scritto:


    Ciao,
    prima di tutto grazie per aver condiviso la tua esperienza.
    Non è che il metodo Close chiude anche la parte server?
    Hai provato questo esempio Qui trovi la guida.
    Ciao e buona programmazione.
    Grazie per avermi risposto. Ho modificato il codice inserendo il metodo Shutdown prima del metodo Close ma non è cambiato niente.
Devi accedere o registrarti per scrivere nel forum
3 risposte