Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

IPCHAT (PROGRAMME DE CHAT COMPLET ET FINI)


Information sur la source

Description

Cliquez pour voir la capture en taille normale
Ce programme permet de chatter par connection directe entre 2 machines (client et serveur).
Il utilise la classe Socket du .Net Framework, sans aucune dll extérieure.
Le programme de chat en lui même est complet et fonctionnel, mais il y a peu de fonctions.
Par contre il peut être très utile pour étudier le fonctionnement de la classe Socket, et la gestion client-serveur.

Tout est dans le zip.
 

Source

  • Imports System.Text
  • Imports System.Net
  • Imports System.Net.Sockets
  • Imports System.IO
  • Public Class frmMain
  • Inherits System.Windows.Forms.Form
  • Dim IPHE As Net.IPHostEntry
  • Dim IPA() As Net.IPAddress
  • Dim HN As String
  • Dim TcpServer As System.Net.Sockets.TcpListener
  • Dim Buffer(1024) As Byte
  • Dim bytes As Integer
  • Dim strTemp As String
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim Retour As DialogResult
  • Public IP As String
  • Public Socket As Socket = Nothing
  • Dim Request As String
  • Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  • IpLocale()
  • If File.Exists("ipchat.ini") Then
  • Dim sr As New StreamReader("ipchat.ini")
  • Dim i As Integer = 0
  • Do Until sr.Peek = -1
  • If i = 0 Then
  • i = 1
  • txtNick.Text = sr.ReadLine
  • Else
  • txtIP.Text = sr.ReadLine
  • End If
  • Loop
  • sr.Close()
  • End If
  • End Sub
  • Private Sub txtIP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtIP.DoubleClick
  • txtIP.Text = ""
  • End Sub
  • Private Sub IpLocale()
  • Dim strIP As String
  • HN = Net.Dns.GetHostName()
  • IPHE = Net.Dns.GetHostByName(HN)
  • IPA = IPHE.AddressList()
  • Dim i As Integer
  • For i = 0 To IPA.GetUpperBound(0)
  • strIP = strIP & IPA(i).ToString() & vbCrLf
  • Next
  • txtIpLocale.Text = strIP
  • End Sub
  • Private Sub Reset()
  • btnConnect.Text = "Se connecter"
  • btnServer.Text = "Héberger"
  • gpbServer.Enabled = True
  • gpbClient.Enabled = True
  • tmrConnect.Enabled = False
  • tmrWait.Enabled = False
  • Socket.Close()
  • Socket = Nothing
  • strTemp = ""
  • sbpConnection.Text = "Non connecté"
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
  • End Sub
  • Private Sub tmrConnect_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrConnect.Tick
  • If Socket.Available > 0 Then
  • bytes = Socket.Receive(Buffer, Buffer.Length, 0)
  • strTemp = strTemp + ascii.ASCII.GetString(Buffer, 0, bytes)
  • Select Case strTemp
  • Case ":connection:CLOSING"
  • Reset()
  • MessageBox.Show("Connexion coupée par le client ou l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • Exit Sub
  • Case ":connection:REFUSED"
  • Reset()
  • MessageBox.Show("Connexion refusée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • Exit Sub
  • Case ":connection:ACCEPTED"
  • MessageBox.Show("Connexion acceptée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Information)
  • strTemp = ""
  • sbpConnection.Text = "Connecté !"
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
  • End Select
  • If strTemp <> "" Then
  • txtAff.Text += strTemp & vbCrLf
  • strTemp = ""
  • End If
  • End If
  • End Sub
  • Private Sub SocketSend(ByVal server As String, ByVal port As Integer)
  • Request = txtNick.Text & " dit : " & vbCrLf & " " & txtMessage.Text
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Request = ""
  • If txtNick.Text = "" Then
  • MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Envoi annulé...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • txtNick.Focus()
  • Exit Sub
  • ElseIf txtMessage.Text = "" Then
  • MessageBox.Show("Vous devez taper un message.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • txtMessage.Focus()
  • Exit Sub
  • End If
  • If Socket Is Nothing Then
  • MessageBox.Show("Vous n'êtes pas connecté." & vbCrLf & "Envoi annulé...", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • Exit Sub
  • End If
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Catch ex As Exception
  • MessageBox.Show("Connexion coupée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • Reset()
  • Exit Sub
  • End Try
  • txtAff.Text += txtNick.Text & " dit : " & vbCrLf & " " & txtMessage.Text & vbCrLf
  • txtMessage.Text = ""
  • End Sub
  • Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
  • If Socket Is Nothing Then
  • MessageBox.Show("Non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • Exit Sub
  • ElseIf txtMessage.Text = "" Then
  • Exit Sub
  • End If
  • SocketSend(IP, 8157)
  • End Sub
  • Private Sub txtAff_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAff.TextChanged
  • If txtAff.Lines.Length > 17 Then
  • txtAff.Text = txtAff.Text.Remove(0, txtAff.Lines(0).Length + 2)
  • End If
  • End Sub
  • Private Sub tmrNow_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrNow.Tick
  • sbpDateSysteme.Text = Date.Now.ToString("dd/MM/yyyy")
  • sbpHeureSysteme.Text = Date.Now.ToString("HH:mm:ss")
  • End Sub
  • #Region "Partie Server"
  • Private Sub btnServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnServer.Click
  • If txtNick.Text = "" Then
  • MessageBox.Show("Vous devez indiquer votre pseudo." & vbCrLf & "Hébergement annulé.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • txtNick.Focus()
  • Exit Sub
  • End If
  • If btnServer.Text = "Héberger" Then
  • btnServer.Text = "Arrêter d'héberger"
  • gpbClient.Enabled = False
  • TcpServer = New Net.Sockets.TcpListener(8157)
  • TcpServer.Start()
  • tmrWait.Enabled = True
  • sbpConnection.Text = "En attente de connexion ..."
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
  • Else
  • btnServer.Text = "Héberger"
  • gpbClient.Enabled = True
  • tmrWait.Enabled = False
  • tmrConnect.Enabled = False
  • TcpServer.Stop()
  • sbpConnection.Text = "Non connecté"
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
  • If Socket Is Nothing Then
  • Exit Sub
  • Else
  • If Socket.Connected = True Then
  • Request = ":connection:CLOSING"
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Socket.Close()
  • Socket = Nothing
  • Catch
  • Socket = Nothing
  • Exit Sub
  • End Try
  • End If
  • End If
  • Exit Sub
  • End If
  • End Sub
  • Private Sub tmrWait_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrWait.Tick
  • If TcpServer.Pending = True Then
  • tmrWait.Enabled = False
  • Socket = TcpServer.AcceptSocket()
  • TcpServer.Stop()
  • If Socket.Connected = True Then
  • If Socket.Available > 0 Then
  • strTemp = ""
  • bytes = Socket.Receive(Buffer, Buffer.Length, 0)
  • strTemp = strTemp + ascii.ASCII.GetString(Buffer, 0, bytes)
  • Retour = MessageBox.Show("Souhaitez vous accepter la connexion en provenance de : " & IPAddress.Parse((CType(Socket.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString & " (" & strTemp & ")" & " ?", "Connexion", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
  • strTemp = ""
  • If Retour = DialogResult.No Then
  • Request = ":connection:REFUSED"
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Socket.Close()
  • Socket = Nothing
  • Catch
  • Socket = Nothing
  • End Try
  • TcpServer.Start()
  • tmrWait.Enabled = True
  • Socket = Nothing
  • Else
  • Request = ":connection:ACCEPTED"
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Catch
  • End Try
  • tmrConnect.Enabled = True
  • sbpConnection.Text = "Connecté !"
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
  • End If
  • End If
  • Else
  • TcpServer.Start()
  • tmrWait.Enabled = True
  • End If
  • End If
  • End Sub
  • #End Region
  • #Region "Partie Client"
  • Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
  • If btnConnect.Text = "Se connecter" Then
  • If Connexion() = True Then
  • tmrConnect.Enabled = True
  • btnConnect.Text = "Se déconnecter"
  • gpbServer.Enabled = False
  • sbpConnection.Text = "En attente de l'acceptation de la connexion..."
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
  • Else
  • Exit Sub
  • End If
  • Else
  • btnConnect.Text = "Se connecter"
  • gpbServer.Enabled = True
  • tmrConnect.Enabled = False
  • sbpConnection.Text = "Non connecté"
  • sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
  • If Socket Is Nothing Then
  • Exit Sub
  • Else
  • If Socket.Connected = True Then
  • Request = ":connection:CLOSING"
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Socket.Close()
  • Catch
  • End Try
  • Socket = Nothing
  • End If
  • End If
  • End If
  • End Sub
  • Private Function Connexion() As Boolean
  • If ValidationIP(txtIP.Text) = False Then
  • MessageBox.Show("Adresse IP non valide !" & vbCrLf & "Connexion annulée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
  • Return False
  • Exit Function
  • Else
  • IP = txtIP.Text
  • End If
  • If txtNick.Text = "" Then
  • MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Connexion annulée...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
  • txtNick.Focus()
  • Return False
  • Exit Function
  • End If
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim Nick As String = txtNick.Text
  • Dim nickSent As [Byte]() = ascii.GetBytes(Nick)
  • Socket = ConnectSocket(IP, 8157)
  • Try
  • Socket.Send(nickSent, nickSent.Length, 0)
  • Catch ex As Exception
  • Return False
  • Exit Function
  • End Try
  • Return True
  • End Function
  • Private Shared Function ConnectSocket(ByVal server As String, ByVal port As Integer) As Socket
  • Dim Socket As Socket = Nothing
  • Dim hostEntry As IPHostEntry = Nothing
  • Try
  • hostEntry = Dns.Resolve(server)
  • Catch ex As Exception
  • If InStr(ex.ToString, "No such host") >= 1 Then
  • MessageBox.Show("Adresse IP non valide ou hôte non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
  • Exit Function
  • End If
  • MessageBox.Show(ex.ToString)
  • End Try
  • Dim address As IPAddress
  • For Each address In hostEntry.AddressList
  • Dim endPoint As New IPEndPoint(address, port)
  • Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
  • Try
  • tempSocket.Connect(endPoint)
  • Catch
  • MessageBox.Show("Erreur lors de la connexion : hôte non joignable.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
  • Exit Function
  • End Try
  • If tempSocket.Connected Then
  • Socket = tempSocket
  • Exit For
  • Else
  • MessageBox.Show("Erreur lors de la connexion : non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
  • Exit Function
  • End If
  • Next address
  • Return Socket
  • End Function
  • Public Function ValidationIP(ByVal strIP As String) As Boolean
  • Try
  • Dim Br1 As String, Br2 As String, Br3 As String, Br4 As String
  • If InStr(strIP, ".") = 0 Then ValidationIP = False : Exit Function
  • Br1 = Microsoft.VisualBasic.Strings.Mid(strIP, 1, InStr(strIP, ".") - 1)
  • Br2 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + 2, (Len(strIP) - InStr(strIP, ".")) + 1)
  • Br2 = Microsoft.VisualBasic.Strings.Left(Br2, InStr(Br2, ".") - 1)
  • Br3 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + 3, Len(strIP))
  • Br3 = Microsoft.VisualBasic.Strings.Left(Br3, InStr(Br3, ".") - 1)
  • Br4 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + Len(Br3) + 4, Len(strIP))
  • If IsNumeric(Br1) = False Or IsNumeric(Br2) = False Or IsNumeric(Br3) = False Or IsNumeric(Br4) = False Then ValidationIP = False : Exit Function
  • If Not (CInt(Br1) >= 0 And CInt(Br1) <= 255) Or Not (CInt(Br2) >= 0 And CInt(Br2) <= 255) Or Not (CInt(Br3) >= 0 And CInt(Br3) <= 255) Or Not (CInt(Br4) >= 0 And CInt(Br4) <= 255) Then ValidationIP = False : Exit Function
  • ValidationIP = True
  • Exit Function
  • Catch
  • ValidationIP = False
  • End Try
  • End Function
  • #End Region
  • Private Sub frmMain_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
  • tmrConnect.Enabled = False
  • Dim sw As New StreamWriter("ipchat.ini", False)
  • sw.WriteLine(txtNick.Text)
  • sw.WriteLine(txtIP.Text)
  • sw.Close()
  • If Socket Is Nothing Then
  • Else
  • If Socket.Connected = True Then
  • Request = ":connection:CLOSING"
  • Dim ascii As Encoding = Encoding.ASCII
  • Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
  • Try
  • Socket.Send(bytesSent, bytesSent.Length, 0)
  • Socket.Close()
  • Catch
  • Exit Sub
  • End Try
  • End If
  • End If
  • End Sub
  • End Class
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Public Class frmMain
    Inherits System.Windows.Forms.Form

    Dim IPHE As Net.IPHostEntry
    Dim IPA() As Net.IPAddress
    Dim HN As String
    Dim TcpServer As System.Net.Sockets.TcpListener
    Dim Buffer(1024) As Byte
    Dim bytes As Integer
    Dim strTemp As String
    Dim ascii As Encoding = Encoding.ASCII
    Dim Retour As DialogResult
    Public IP As String
    Public Socket As Socket = Nothing
    Dim Request As String

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        IpLocale()
        If File.Exists("ipchat.ini") Then
            Dim sr As New StreamReader("ipchat.ini")
            Dim i As Integer = 0
            Do Until sr.Peek = -1
                If i = 0 Then
                    i = 1
                    txtNick.Text = sr.ReadLine
                Else
                    txtIP.Text = sr.ReadLine
                End If
            Loop
            sr.Close()
        End If
    End Sub

    Private Sub txtIP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtIP.DoubleClick
        txtIP.Text = ""
    End Sub

    Private Sub IpLocale()
        Dim strIP As String
        HN = Net.Dns.GetHostName()
        IPHE = Net.Dns.GetHostByName(HN)
        IPA = IPHE.AddressList()
        Dim i As Integer
        For i = 0 To IPA.GetUpperBound(0)
            strIP = strIP & IPA(i).ToString() & vbCrLf
        Next
        txtIpLocale.Text = strIP
    End Sub

    Private Sub Reset()
        btnConnect.Text = "Se connecter"
        btnServer.Text = "Héberger"
        gpbServer.Enabled = True
        gpbClient.Enabled = True
        tmrConnect.Enabled = False
        tmrWait.Enabled = False
        Socket.Close()
        Socket = Nothing
        strTemp = ""
        sbpConnection.Text = "Non connecté"
        sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
    End Sub

    Private Sub tmrConnect_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrConnect.Tick
        If Socket.Available > 0 Then
            bytes = Socket.Receive(Buffer, Buffer.Length, 0)
            strTemp = strTemp + ascii.ASCII.GetString(Buffer, 0, bytes)
            Select Case strTemp
                Case ":connection:CLOSING"
                    Reset()
                    MessageBox.Show("Connexion coupée par le client ou l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Exit Sub
                Case ":connection:REFUSED"
                    Reset()
                    MessageBox.Show("Connexion refusée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Exit Sub
                Case ":connection:ACCEPTED"
                    MessageBox.Show("Connexion acceptée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    strTemp = ""
                    sbpConnection.Text = "Connecté !"
                    sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
            End Select
            If strTemp <> "" Then
                txtAff.Text += strTemp & vbCrLf
                strTemp = ""
            End If
        End If
    End Sub

    Private Sub SocketSend(ByVal server As String, ByVal port As Integer)
        Request = txtNick.Text & " dit : " & vbCrLf & "  " & txtMessage.Text
        Dim ascii As Encoding = Encoding.ASCII
        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
        Request = ""
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Envoi annulé...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Exit Sub
        ElseIf txtMessage.Text = "" Then
            MessageBox.Show("Vous devez taper un message.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtMessage.Focus()
            Exit Sub
        End If

        If Socket Is Nothing Then
            MessageBox.Show("Vous n'êtes pas connecté." & vbCrLf & "Envoi annulé...", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If

        Try
            Socket.Send(bytesSent, bytesSent.Length, 0)
        Catch ex As Exception
            MessageBox.Show("Connexion coupée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Reset()
            Exit Sub
        End Try
        txtAff.Text += txtNick.Text & " dit : " & vbCrLf & "  " & txtMessage.Text & vbCrLf
        txtMessage.Text = ""
    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        If Socket Is Nothing Then
            MessageBox.Show("Non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        ElseIf txtMessage.Text = "" Then
            Exit Sub
        End If
        SocketSend(IP, 8157)
    End Sub

    Private Sub txtAff_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAff.TextChanged
        If txtAff.Lines.Length > 17 Then
            txtAff.Text = txtAff.Text.Remove(0, txtAff.Lines(0).Length + 2)
        End If
    End Sub

    Private Sub tmrNow_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrNow.Tick
        sbpDateSysteme.Text = Date.Now.ToString("dd/MM/yyyy")
        sbpHeureSysteme.Text = Date.Now.ToString("HH:mm:ss")
    End Sub

#Region "Partie Server"

    Private Sub btnServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnServer.Click
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez indiquer votre pseudo." & vbCrLf & "Hébergement annulé.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Exit Sub
        End If
        If btnServer.Text = "Héberger" Then
            btnServer.Text = "Arrêter d'héberger"
            gpbClient.Enabled = False
            TcpServer = New Net.Sockets.TcpListener(8157)
            TcpServer.Start()
            tmrWait.Enabled = True
            sbpConnection.Text = "En attente de connexion ..."
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
        Else
            btnServer.Text = "Héberger"
            gpbClient.Enabled = True
            tmrWait.Enabled = False
            tmrConnect.Enabled = False
            TcpServer.Stop()
            sbpConnection.Text = "Non connecté"
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
            If Socket Is Nothing Then
                Exit Sub
            Else
                If Socket.Connected = True Then
                    Request = ":connection:CLOSING"
                    Dim ascii As Encoding = Encoding.ASCII
                    Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                    Try
                        Socket.Send(bytesSent, bytesSent.Length, 0)
                        Socket.Close()
                        Socket = Nothing
                    Catch
                        Socket = Nothing
                        Exit Sub
                    End Try
                End If
            End If
            Exit Sub
        End If
    End Sub

    Private Sub tmrWait_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrWait.Tick
        If TcpServer.Pending = True Then
            tmrWait.Enabled = False
            Socket = TcpServer.AcceptSocket()
            TcpServer.Stop()
            If Socket.Connected = True Then
                If Socket.Available > 0 Then
                    strTemp = ""
                    bytes = Socket.Receive(Buffer, Buffer.Length, 0)
                    strTemp = strTemp + ascii.ASCII.GetString(Buffer, 0, bytes)
                    Retour = MessageBox.Show("Souhaitez vous accepter la connexion en provenance de : " & IPAddress.Parse((CType(Socket.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString & " (" & strTemp & ")" & " ?", "Connexion", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    strTemp = ""
                    If Retour = DialogResult.No Then
                        Request = ":connection:REFUSED"
                        Dim ascii As Encoding = Encoding.ASCII
                        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                        Try
                            Socket.Send(bytesSent, bytesSent.Length, 0)
                            Socket.Close()
                            Socket = Nothing
                        Catch
                            Socket = Nothing
                        End Try
                        TcpServer.Start()
                        tmrWait.Enabled = True
                        Socket = Nothing
                    Else
                        Request = ":connection:ACCEPTED"
                        Dim ascii As Encoding = Encoding.ASCII
                        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                        Try
                            Socket.Send(bytesSent, bytesSent.Length, 0)
                        Catch
                        End Try
                        tmrConnect.Enabled = True
                        sbpConnection.Text = "Connecté !"
                        sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
                    End If
                End If
            Else
                TcpServer.Start()
                tmrWait.Enabled = True
            End If
        End If
    End Sub

#End Region

#Region "Partie Client"

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        If btnConnect.Text = "Se connecter" Then
            If Connexion() = True Then
                tmrConnect.Enabled = True
                btnConnect.Text = "Se déconnecter"
                gpbServer.Enabled = False
                sbpConnection.Text = "En attente de l'acceptation de la connexion..."
                sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
            Else
                Exit Sub
            End If
        Else
            btnConnect.Text = "Se connecter"
            gpbServer.Enabled = True
            tmrConnect.Enabled = False
            sbpConnection.Text = "Non connecté"
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
            If Socket Is Nothing Then
                Exit Sub
            Else
                If Socket.Connected = True Then
                    Request = ":connection:CLOSING"
                    Dim ascii As Encoding = Encoding.ASCII
                    Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                    Try
                        Socket.Send(bytesSent, bytesSent.Length, 0)
                        Socket.Close()
                    Catch
                    End Try
                    Socket = Nothing
                End If
            End If
        End If
    End Sub

    Private Function Connexion() As Boolean
        If ValidationIP(txtIP.Text) = False Then
            MessageBox.Show("Adresse IP non valide !" & vbCrLf & "Connexion annulée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        Else
            IP = txtIP.Text
        End If
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Connexion annulée...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Return False
            Exit Function
        End If
        Dim ascii As Encoding = Encoding.ASCII
        Dim Nick As String = txtNick.Text
        Dim nickSent As [Byte]() = ascii.GetBytes(Nick)
        Socket = ConnectSocket(IP, 8157)
        Try
            Socket.Send(nickSent, nickSent.Length, 0)
        Catch ex As Exception
            Return False
            Exit Function
        End Try
        Return True
    End Function

    Private Shared Function ConnectSocket(ByVal server As String, ByVal port As Integer) As Socket
        Dim Socket As Socket = Nothing
        Dim hostEntry As IPHostEntry = Nothing
        Try
            hostEntry = Dns.Resolve(server)
        Catch ex As Exception
            If InStr(ex.ToString, "No such host") >= 1 Then
                MessageBox.Show("Adresse IP non valide ou hôte non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End If
            MessageBox.Show(ex.ToString)
        End Try

        Dim address As IPAddress

        For Each address In hostEntry.AddressList
            Dim endPoint As New IPEndPoint(address, port)
            Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

            Try
                tempSocket.Connect(endPoint)
            Catch
                MessageBox.Show("Erreur lors de la connexion : hôte non joignable.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End Try

            If tempSocket.Connected Then
                Socket = tempSocket
                Exit For
            Else
                MessageBox.Show("Erreur lors de la connexion : non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End If

        Next address

        Return Socket
    End Function

    Public Function ValidationIP(ByVal strIP As String) As Boolean
        Try
            Dim Br1 As String, Br2 As String, Br3 As String, Br4 As String
            If InStr(strIP, ".") = 0 Then ValidationIP = False : Exit Function
            Br1 = Microsoft.VisualBasic.Strings.Mid(strIP, 1, InStr(strIP, ".") - 1)
            Br2 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + 2, (Len(strIP) - InStr(strIP, ".")) + 1)
            Br2 = Microsoft.VisualBasic.Strings.Left(Br2, InStr(Br2, ".") - 1)
            Br3 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + 3, Len(strIP))
            Br3 = Microsoft.VisualBasic.Strings.Left(Br3, InStr(Br3, ".") - 1)
            Br4 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + Len(Br3) + 4, Len(strIP))
            If IsNumeric(Br1) = False Or IsNumeric(Br2) = False Or IsNumeric(Br3) = False Or IsNumeric(Br4) = False Then ValidationIP = False : Exit Function
            If Not (CInt(Br1) >= 0 And CInt(Br1) <= 255) Or Not (CInt(Br2) >= 0 And CInt(Br2) <= 255) Or Not (CInt(Br3) >= 0 And CInt(Br3) <= 255) Or Not (CInt(Br4) >= 0 And CInt(Br4) <= 255) Then ValidationIP = False : Exit Function
            ValidationIP = True
            Exit Function
        Catch
            ValidationIP = False
        End Try
    End Function
#End Region

    Private Sub frmMain_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        tmrConnect.Enabled = False
        Dim sw As New StreamWriter("ipchat.ini", False)
        sw.WriteLine(txtNick.Text)
        sw.WriteLine(txtIP.Text)
        sw.Close()
        If Socket Is Nothing Then
        Else
            If Socket.Connected = True Then
                Request = ":connection:CLOSING"
                Dim ascii As Encoding = Encoding.ASCII
                Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                Try
                    Socket.Send(bytesSent, bytesSent.Length, 0)
                    Socket.Close()
                Catch
                    Exit Sub
                End Try
            End If
        End If
    End Sub

End Class

Conclusion

Le code est très certainement améliorable, n'hésitez pas dans les commentaires ;)
Ce code servira de base a un projet bien plus important, il fera office de netcode dans un jeu multijoueur.

Spéciale dédicace a Ulmo, l'apprenti programmeur qui dépasse le maître :p
 

Fichier Zip

Pour les "Membres Club", vous pouvez télécharger directement un fichier contenu dans le zip sans télécharger le zip en entier !

Télécharger le zip

Commentaires et avis

signaler à un administrateur
Commentaire de CrazyMan19 le 04/05/2005 03:18:20

est ce que t l as testé ds le Net avec qqn autre qui n est pas ds le même Network , et est ce que ca marché !??

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 03:25:26

Ca marche en local et sur le net ;)
(oui sur mon screenshot c'est en local, mais si ca ne pose aucun problème sur le net, a condition que le pare feu du serveur soit bien configuré ...)

signaler à un administrateur
Commentaire de liquide le 04/05/2005 08:46:52

salut, juste mon avis, je me demande ce qu'il se passerait coté client si l'hote etait trop rapide a ecrire et faisait des send rapidement.

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 09:09:10

Petite question cela marche sur un reseau local parce que j'essaye avec les différentes adresses ip du reseau et ça marche pas?
dans la partie hote j'ai bien mon adresse ip en revanche dans la partie cliente j'ai beau balayé mon réseau et il me repond hote non joingnable.
je passe par un switch en interne et un routeur pour le net,
ça marche chez quelqu'un

signaler à un administrateur
Commentaire de liquide le 04/05/2005 09:48:01

en theorie un socket est capable de se connecter sur toutes sortes d'IP(loacal, internet). ce qui pourrait bloquer c'est peut etre le port, ou un firewall eventuellement.
D'un 1er oeil(En attendant que tom_killers apporte des info supplémentaires), je reste persuadé que ce chat a plutot été codé pc sur meme pc, avec la meme IP hote et client.

signaler à un administrateur
Commentaire de Amigalopin le 04/05/2005 09:50:05

Bonjour,

Vraiment un beau travail.
Je viens de le tester au travers du réseau de mon boulot (plus de 12000 PC, pleins de switch, serveurs, routeurs, etc....)

Je suis à un endroit, et mon collègue se situe à près de 80 km de moi, bien entendu sur un autre sous-réseau: pas de problème pour se connecter.

et c'est super rapide.

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 11:39:30

sous quelle config tu travailles amigalopin
personnellement je suis sous XP sp2 et j'ai desactivé le firewall windows et mon antivirus

signaler à un administrateur
Commentaire de Amigalopin le 04/05/2005 11:57:36

XP SP2.
Réseau interne à la société.
Chaque site possède sont propre sous-réseau.
Le tout interconnecté .

Antivirus McAfee toujours activé et le firewall, c'est la passerelle internet qui s'en charge. (donc, pas essayé vers l'extérieur du réseau... puis, c'est pas hum... officiellement autorisé... mais c'est pour faire des tests... )

signaler à un administrateur
Commentaire de XtremDuke le 04/05/2005 11:59:21

Et un Chat de plus, un !

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 12:08:42

Salut à tous

Pour répondre a vos quelques questions : mon chat a été testé sur mon reseau local (4 pc reliés par un switch).
Aucune de ces machines n'a de firewall (le reseau entier est firewallé par IpCop) et sont sous XP sp2 (2 d'entre elles).
Pas de problème a signaler, ca a toujours fonctionné correctement.
Il a également été testé a travers internet avec des amis qui ont acceptés de faire le test.
La par contre, il y a eu souvent des problèmes, toujours dus a la même chose : le firewall ...
Apres configuration des firewall ca a marché avec tout le monde.
Je ne prétend pas que ca marche forcément du premier coup chez tout le monde, ca dépend vraiment de la configuration de chacun.

@liquide : même si l'hôte écrit extrêmement vite et n'importe quoi (genre : bvcxbvsc{ENTER} ), je n'ai pas réussi a faire planter le prog (en local en tout cas, j'ai jamais essayer d'y aller comme un porc sur le net)
Après tu peut toujours essayer de le faire planter, tu y arrivera forcément en bourrinant ;)

@Amigalopin : merci pour ton soutient, stp met une note :p

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 12:11:04

@XtremDuke : c'est vrai que des chat en VB.NET qui fonctionnent en utilisant uniquement les fct du .Net Framework y'en a des masses phénoménales ;)

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 12:12:42

de quoi cela peut il provenir quequin à un idée(les lumineuses sont préférables)
J'aimerais bien que ça marche je trouve cela très intéressant
au fait Xtremeduke je trouve que tu ressembles à Deschamps!

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 12:14:40

@TOTOCHITO : si tu veut on peut faire un test sur le net, si ca t'intéresse donne moi ton adresse msn par MP (si tu en a une ;) )

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 12:24:53

au boulot j'en ai pas, juste une question pour que cela marche il faut que l'appli tourne sur les 2 postes?
Sinon il faudrait que je fasse l'essai à la maison avec l'adresse ip en directe

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 12:28:40

Oui il faut que l'appli tourne sur les deux poste, avec un des deux poste qui héberge, et un autre qui se connecte sur celui qui héberge ;)
Le tout c'est de pas se planter dans les IP...
Dans la partie "Client", il faut metre l'IP de l'hôte distant ...

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 12:36:56

Donc dans l'hote s'affiche l'adresse IP de mon poste et en face l'appli doit tourner , aussi dans la partie cliente si je tape   son adresse ip cela doit marcher(il se fou du masque de sous reseau et de la passerelle)
pourtant lorsque je ping le reseau je n'ai aucun probleme

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 12:51:31

Il faut que tu clique sur "Héberger" sur le pc qui va te servir d'hôte, et tu copie l'IP de ce PC (verifie que t'a qu'une IP) dans la partie Client de l'autre PC, et tu clique sur "Se connecter".
Laisse tomber les masques et les passerelles, verifie juste tes IP, et vérifie que t'en a qu'une sur l'hôte, sinon il se peut que tu ai indiqué la mauvaise ...

signaler à un administrateur
Commentaire de liquide le 04/05/2005 13:17:09

tom_killers, je ne dis pas qu'en tapant vite ca va le faire planter, je me demandais seulement si en envoyant des données via le socket d'une facon rapide, ca n'allait pas le faire planter c'est tout. il ne fallait pas le prendre mal, ce n'etait pas mon but.

signaler à un administrateur
Commentaire de liquide le 04/05/2005 13:19:54

pour le chat en .net, c'est vrai que c'est rare d'autant plus que celui sur lequel je bosse en mutli-client n'est pas ma propriété alors je ne peux pas le passer, dommage.

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 13:23:28

@liquide :
- Je ne l'ai pas pris mal du tout, ya pas de pbm ;)
- Ya pas moyen que tu demande a propriétaire si il peut      diffuser son code ? (le multi client ca m'intéresse, c'est une des choses que j'ai prévu de faire sur IpChat ;) )
Sinon c'est pas grave je me débrouillerai :)

signaler à un administrateur
Commentaire de liquide le 04/05/2005 13:30:02

je vais lui demandé, lol ce que je pense, de comment je verais les choses, d'un moyen de faire, ou meme des basic connaissance que j'ai pu acquérir.. c'est ma propriété lol, je peux donner sans pb, je laisse mon msn, je pense dans mon profil.
sinon liquide_vaisselle_76@hotmail.fr.

signaler à un administrateur
Commentaire de chris81 le 04/05/2005 14:23:58

j'avais deja trouve une source comme la tienne mise a part quelle tenait en 30 lignes. Si je la retrouve je te la fait passer. a+

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 14:26:56

En VB.NET et sans dll ?
Vraiment, ca m'intéresse ;)

signaler à un administrateur
Commentaire de chris81 le 04/05/2005 14:37:10

comme toi il utilisait les sockets donc aucune dll, des j'arrive chez moi ce soir je te le fait passer

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 14:43:25

T'es absolument certain qu'il arrive a faire ca sans activex et sans rien intégrer d'extérieur dans le projet ?
Suis vraiment impréssionné, j'attends de voir ;)

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 15:15:42

merci tom killer ça marche, en fait je faisait une mauvaise manip
bravo encore pour ta source

signaler à un administrateur
Commentaire de TOTOCHITO le 04/05/2005 15:15:56

merci tom killer ça marche, en fait je faisais une mauvaise manip
bravo encore pour ta source

signaler à un administrateur
Commentaire de chris81 le 04/05/2005 19:45:25

voici l'adresse ou je l'ai mis
http://www.vbfrance.com/code.aspx?ID=31211

signaler à un administrateur
Commentaire de TOM_KILLERz le 04/05/2005 20:01:18

1. C'est pas du VB.NET
2. Je compte 152 lignes
3. Il faut 2 solutions, un client et un serveur
4. Ya pas de gestions d'erreurs
5. Y'a pas d'interface graphique
6. Tu a posté une source en C# sur VBFrance, c'est assez fort !!!

Je trouve que ca fait quand même beaucoup ;)

signaler à un administrateur
Commentaire de dragon le 10/05/2005 20:04:31

pour répondre, j'utilise le socket en .Net pour faire un serveur de base de donnée.

Mon serveur reçoi plus de 100 requête par seconde à certain moment d'une même personne ou de personnes différentes.

ça amrche numéro 1, les requêtes en trop se stocke dans une File et dès que le code peut, il prendre la réception suivante (l'idéal, c'est que ça attende pas comme ce que j'ai fais, mais là ça dépend de ton code)

pour le multi client sur un même port, rien de plus facile, faut passer l'IP et un code avant d'envoyer le message pour savoir si le client doit ignorer ou lire le mesage. Si c'est un message privé, le serveur dois ouvrir un port et envoyer le numéro sur un port public. Ensuite, les 2 pc se connecte entre eux sur le port privé.

mais bon, je peux pas diffusé mon code, c'est pour ma job, mais je voulais répondre au question de ce qui se passe lorsqu'on flood le serveur et commetn faire un chat muti usager sur un même port

en passant, avant de me faire demander, pour avoir l'IP c'est :

    Private IP As String = ""

    Public Function getIP() As String
        If IP = "" Then
            IP = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName).AddressList.GetValue(0).ToString
        End If
        Return IP
    End Function

signaler à un administrateur
Commentaire de anthonygego le 12/08/2005 18:58:53

Quand tu envoie et reçois les textes, tu encodes en ASCII américain, résultat, quand on tape un accent, il reçoit autre chose, je te conseille de remplacer :

   Encoding.ASCII.GetBytes et GetString
par
   Encoding.UTF8.GetBytes et GetString

signaler à un administrateur
Commentaire de TOM_KILLERz le 13/08/2005 00:08:56

Hmmm ...
Absolument exact, j'avais pas fait attention ;)

Mci beaucoup, je changerai ca dès que j'ai quelques secondes de libre :p

signaler à un administrateur
Commentaire de Le_proprio_de_mykeyes le 19/08/2005 20:38:25

Si on veut, on pourrait inclure une transmission de fichiers dans le programme, ce que j'ai fait et maintenant j'utilise votre programme. Si ça vous intéresse, il suffit de changer frmMain.vb par ce frmMain.vb ci:


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

Public Class frmMain
    Inherits System.Windows.Forms.Form
    Private components As System.ComponentModel.IContainer
    WithEvents Friend txtIpLocale As System.Windows.Forms.TextBox
    WithEvents Friend sbpDateSysteme As System.Windows.Forms.StatusBarPanel
    WithEvents Friend btnConnect As System.Windows.Forms.Button
    WithEvents Friend txtIP As System.Windows.Forms.TextBox
    WithEvents Friend gpbServer As System.Windows.Forms.GroupBox
    WithEvents Friend txtNick As System.Windows.Forms.TextBox
    WithEvents Friend sbpHeureSysteme As System.Windows.Forms.StatusBarPanel
    WithEvents Friend tmrConnect As System.Windows.Forms.Timer
    WithEvents Friend lblNick As System.Windows.Forms.Label
    Private button1 As System.Windows.Forms.Button
    WithEvents Friend txtMessage As System.Windows.Forms.TextBox
    WithEvents Friend btnSend As System.Windows.Forms.Button
    WithEvents Friend sbMain As System.Windows.Forms.StatusBar
    WithEvents Friend txtAff As System.Windows.Forms.TextBox
    WithEvents Friend tmrNow As System.Windows.Forms.Timer
    WithEvents Friend lblTOM_KILLERz As System.Windows.Forms.Label
    WithEvents Friend btnServer As System.Windows.Forms.Button
    WithEvents Friend tmrWait As System.Windows.Forms.Timer
    Private saveFile As System.Windows.Forms.SaveFileDialog
    Private sendFile As System.Windows.Forms.OpenFileDialog
    WithEvents Friend sbpConnection As System.Windows.Forms.StatusBarPanel
    WithEvents Friend gpbClient As System.Windows.Forms.GroupBox
    
#Region " Code généré par le Concepteur Windows Form "

    Public Sub New()
        MyBase.New()

        'Cet appel est requis par le Concepteur Windows Form.
        InitializeComponent()
        Application.EnableVisualStyles()
        Application.DoEvents()

        'Ajoutez une initialisation quelconque après l'appel InitializeComponent()

    End Sub

    'La méthode substituée Dispose du formulaire pour nettoyer la liste des composants.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Requis par le Concepteur Windows Form

    'REMARQUE : la procédure suivante est requise par le Concepteur Windows Form
    'Elle peut être modifiée en utilisant le Concepteur Windows Form.  
    'Ne la modifiez pas en utilisant l'éditeur de code.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.components = New System.ComponentModel.Container
Me.gpbClient = New System.Windows.Forms.GroupBox
Me.sbpConnection = New System.Windows.Forms.StatusBarPanel
Me.sendFile = New System.Windows.Forms.OpenFileDialog
Me.saveFile = New System.Windows.Forms.SaveFileDialog
Me.tmrWait = New System.Windows.Forms.Timer(Me.components)
Me.btnServer = New System.Windows.Forms.Button
Me.lblTOM_KILLERz = New System.Windows.Forms.Label
Me.tmrNow = New System.Windows.Forms.Timer(Me.components)
Me.txtAff = New System.Windows.Forms.TextBox
Me.sbMain = New System.Windows.Forms.StatusBar
Me.btnSend = New System.Windows.Forms.Button
Me.txtMessage = New System.Windows.Forms.TextBox
Me.button1 = New System.Windows.Forms.Button
Me.lblNick = New System.Windows.Forms.Label
Me.tmrConnect = New System.Windows.Forms.Timer(Me.components)
Me.sbpHeureSysteme = New System.Windows.Forms.StatusBarPanel
Me.txtNick = New System.Windows.Forms.TextBox
Me.gpbServer = New System.Windows.Forms.GroupBox
Me.txtIP = New System.Windows.Forms.TextBox
Me.btnConnect = New System.Windows.Forms.Button
Me.sbpDateSysteme = New System.Windows.Forms.StatusBarPanel
Me.txtIpLocale = New System.Windows.Forms.TextBox
Me.gpbClient.SuspendLayout
CType(Me.sbpConnection,System.ComponentModel.ISupportInitialize).BeginInit
CType(Me.sbpHeureSysteme,System.ComponentModel.ISupportInitialize).BeginInit
Me.gpbServer.SuspendLayout
CType(Me.sbpDateSysteme,System.ComponentModel.ISupportInitialize).BeginInit
Me.SuspendLayout
'
'gpbClient
'
Me.gpbClient.Controls.Add(Me.txtIP)
Me.gpbClient.Controls.Add(Me.btnConnect)
Me.gpbClient.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.gpbClient.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.gpbClient.Location = New System.Drawing.Point(20, 8)
Me.gpbClient.Name = "gpbClient"
Me.gpbClient.Size = New System.Drawing.Size(136, 88)
Me.gpbClient.TabIndex = 1
Me.gpbClient.TabStop = false
Me.gpbClient.Text = "Client"
'
'sbpConnection
'
Me.sbpConnection.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring
Me.sbpConnection.Text = "Non connecté"
Me.sbpConnection.ToolTipText = "Etat de la connexion"
Me.sbpConnection.Width = 286
'
'sendFile
'
Me.sendFile.Filter = "Tous les fichiers (*.*) |*.*"
Me.sendFile.InitialDirectory = "C:\"
Me.sendFile.RestoreDirectory = true
Me.sendFile.Title = "Envoyer un fichier..."
'
'saveFile
'
Me.saveFile.DefaultExt = "txt"
Me.saveFile.Filter = "Tous les fichiers (*.*)|*.*"
Me.saveFile.RestoreDirectory = true
'
'tmrWait
'
Me.tmrWait.Interval = 200
'
'btnServer
'
Me.btnServer.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.btnServer.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.btnServer.Location = New System.Drawing.Point(30, 48)
Me.btnServer.Name = "btnServer"
Me.btnServer.Size = New System.Drawing.Size(80, 32)
Me.btnServer.TabIndex = 0
Me.btnServer.Text = "Héberger"
'
'lblTOM_KILLERz
'
Me.lblTOM_KILLERz.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.lblTOM_KILLERz.ForeColor = System.Drawing.Color.DarkBlue
Me.lblTOM_KILLERz.Location = New System.Drawing.Point(215, 456)
Me.lblTOM_KILLERz.Name = "lblTOM_KILLERz"
Me.lblTOM_KILLERz.RightToLeft = System.Windows.Forms.RightToLeft.No
Me.lblTOM_KILLERz.TabIndex = 8
Me.lblTOM_KILLERz.Text = "TOM_KILLERz"
Me.lblTOM_KILLERz.TextAlign = System.Drawing.ContentAlignment.MiddleCenter
'
'tmrNow
'
Me.tmrNow.Enabled = true
Me.tmrNow.Interval = 1000
'
'txtAff
'
Me.txtAff.BackColor = System.Drawing.SystemColors.ControlLightLight
Me.txtAff.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.txtAff.Location = New System.Drawing.Point(12, 132)
Me.txtAff.Multiline = true
Me.txtAff.Name = "txtAff"
Me.txtAff.ReadOnly = true
Me.txtAff.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtAff.Size = New System.Drawing.Size(300, 216)
Me.txtAff.TabIndex = 9
Me.txtAff.TabStop = false
Me.txtAff.Text = ""
'
'sbMain
'
Me.sbMain.Location = New System.Drawing.Point(0, 482)
Me.sbMain.Name = "sbMain"
Me.sbMain.Panels.AddRange(New System.Windows.Forms.StatusBarPanel() {Me.sbpConnection, Me.sbpDateSysteme, Me.sbpHeureSysteme})
Me.sbMain.ShowPanels = true
Me.sbMain.Size = New System.Drawing.Size(322, 22)
Me.sbMain.TabIndex = 11
'
'btnSend
'
Me.btnSend.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.btnSend.Location = New System.Drawing.Point(232, 384)
Me.btnSend.Name = "btnSend"
Me.btnSend.Size = New System.Drawing.Size(75, 40)
Me.btnSend.TabIndex = 3
Me.btnSend.Text = "Envoyer le message"
'
'txtMessage
'
Me.txtMessage.Font = New System.Drawing.Font("Microsoft Sans Serif", 9.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.txtMessage.Location = New System.Drawing.Point(12, 356)
Me.txtMessage.Multiline = true
Me.txtMessage.Name = "txtMessage"
Me.txtMessage.Size = New System.Drawing.Size(216, 92)
Me.txtMessage.TabIndex = 10
Me.txtMessage.Text = ""
'
'button1
'
Me.button1.Location = New System.Drawing.Point(20, 460)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(155, 20)
Me.button1.TabIndex = 12
Me.button1.Text = "Envoyer un fichier..."
AddHandler Me.button1.Click, AddressOf Me.sendFiler
'
'lblNick
'
Me.lblNick.Location = New System.Drawing.Point(12, 100)
Me.lblNick.Name = "lblNick"
Me.lblNick.Size = New System.Drawing.Size(80, 23)
Me.lblNick.TabIndex = 4
Me.lblNick.Text = "Votre Pseudo : "
Me.lblNick.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
'
'tmrConnect
'
Me.tmrConnect.Interval = 75
'
'sbpHeureSysteme
'
Me.sbpHeureSysteme.Alignment = System.Windows.Forms.HorizontalAlignment.Center
Me.sbpHeureSysteme.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents
Me.sbpHeureSysteme.ToolTipText = "Heure Système"
Me.sbpHeureSysteme.Width = 10
'
'txtNick
'
Me.txtNick.Location = New System.Drawing.Point(96, 104)
Me.txtNick.Name = "txtNick"
Me.txtNick.Size = New System.Drawing.Size(216, 20)
Me.txtNick.TabIndex = 0
Me.txtNick.Text = ""
'
'gpbServer
'
Me.gpbServer.Controls.Add(Me.txtIpLocale)
Me.gpbServer.Controls.Add(Me.btnServer)
Me.gpbServer.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.gpbServer.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.gpbServer.Location = New System.Drawing.Point(168, 8)
Me.gpbServer.Name = "gpbServer"
Me.gpbServer.Size = New System.Drawing.Size(136, 88)
Me.gpbServer.TabIndex = 4
Me.gpbServer.TabStop = false
Me.gpbServer.Text = "Hôte"
'
'txtIP
'
Me.txtIP.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.txtIP.Location = New System.Drawing.Point(16, 20)
Me.txtIP.Name = "txtIP"
Me.txtIP.Size = New System.Drawing.Size(108, 20)
Me.txtIP.TabIndex = 0
Me.txtIP.Text = "IP de l'hôte"
'
'btnConnect
'
Me.btnConnect.FlatStyle = System.Windows.Forms.FlatStyle.System
Me.btnConnect.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.btnConnect.Location = New System.Drawing.Point(30, 48)
Me.btnConnect.Name = "btnConnect"
Me.btnConnect.Size = New System.Drawing.Size(80, 32)
Me.btnConnect.TabIndex = 1
Me.btnConnect.Text = "Se connecter"
'
'sbpDateSysteme
'
Me.sbpDateSysteme.Alignment = System.Windows.Forms.HorizontalAlignment.Center
Me.sbpDateSysteme.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Contents
Me.sbpDateSysteme.ToolTipText = "Date Système"
Me.sbpDateSysteme.Width = 10
'
'txtIpLocale
'
Me.txtIpLocale.Font = New System.Drawing.Font("Microsoft Sans Serif", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0,Byte))
Me.txtIpLocale.Location = New System.Drawing.Point(16, 20)
Me.txtIpLocale.Multiline = true
Me.txtIpLocale.Name = "txtIpLocale"
Me.txtIpLocale.ReadOnly = true
Me.txtIpLocale.ScrollBars = System.Windows.Forms.ScrollBars.Vertical
Me.txtIpLocale.Size = New System.Drawing.Size(108, 20)
Me.txtIpLocale.TabIndex = 1
Me.txtIpLocale.Text = ""
Me.txtIpLocale.TextAlign = System.Windows.Forms.HorizontalAlignment.Center
'
'frmMain
'
Me.AcceptButton = Me.btnSend
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.BackColor = System.Drawing.Color.LightSteelBlue
Me.ClientSize = New System.Drawing.Size(322, 504)
Me.Controls.Add(Me.button1)
Me.Controls.Add(Me.sbMain)
Me.Controls.Add(Me.txtMessage)
Me.Controls.Add(Me.txtAff)
Me.Controls.Add(Me.lblTOM_KILLERz)
Me.Controls.Add(Me.btnSend)
Me.Controls.Add(Me.lblNick)
Me.Controls.Add(Me.txtNick)
Me.Controls.Add(Me.gpbClient)
Me.Controls.Add(Me.gpbServer)
Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
Me.MaximizeBox = false
Me.Name = "frmMain"
Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
Me.Text = "MiniChat"
Me.gpbClient.ResumeLayout(false)
CType(Me.sbpConnection,System.ComponentModel.ISupportInitialize).EndInit
CType(Me.sbpHeureSysteme,System.ComponentModel.ISupportInitialize).EndInit
Me.gpbServer.ResumeLayout(false)
CType(Me.sbpDateSysteme,System.ComponentModel.ISupportInitialize).EndInit
Me.ResumeLayout(false)
End Sub

#End Region

    Dim IPHE As Net.IPHostEntry
    Dim IPA() As Net.IPAddress
    Dim HN As String
    Dim TcpServer As System.Net.Sockets.TcpListener
    Dim Buffer(28394909) As Byte
    Dim bytes As Integer
    Dim strTemp As String
    Dim ascii As Encoding = Encoding.UTF8
    Dim Retour As DialogResult
    Public IP As String
    Public Socket As Socket = Nothing
    Dim Request As String

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        IpLocale()
        If File.Exists("ipchat.ini") Then
            Dim sr As New StreamReader("ipchat.ini")
            Dim i As Integer = 0
            Do Until sr.Peek = -1
                If i = 0 Then
                    i = 1
                    txtNick.Text = sr.ReadLine
                Else
                    txtIP.Text = sr.ReadLine
                End If
            Loop
            sr.Close()
        End If
    End Sub

    Private Sub txtIP_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtIP.DoubleClick
        txtIP.Text = ""
    End Sub

    Private Sub IpLocale()
        Dim strIP As String
        HN = Net.Dns.GetHostName()
        IPHE = Net.Dns.GetHostByName(HN)
        IPA = IPHE.AddressList()
        Dim i As Integer
        For i = 0 To IPA.GetUpperBound(0)
            strIP = strIP & IPA(i).ToString() & vbCrLf
        Next
        txtIpLocale.Text = strIP
    End Sub

    Private Sub Reset()
        btnConnect.Text = "Se connecter"
        btnServer.Text = "Héberger"
        gpbServer.Enabled = True
        gpbClient.Enabled = True
        tmrConnect.Enabled = False
        tmrWait.Enabled = False
        Socket.Close()
        Socket = Nothing
        strTemp = ""
        sbpConnection.Text = "Non connecté"
        sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
    End Sub

    Private Sub tmrConnect_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrConnect.Tick
        If Socket.Available > 0 Then
            bytes = Socket.Receive(Buffer, Buffer.Length, 0)
            strTemp = strTemp + ascii.UTF8.GetString(Buffer, 0, bytes)
            Select Case strTemp
                Case ":connection:CLOSING"
                    Reset()
                    MessageBox.Show("Connexion coupée par le client ou l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Exit Sub
                Case ":connection:REFUSED"
                    Reset()
                    MessageBox.Show("Connexion refusée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                    Exit Sub
                Case ":connection:ACCEPTED"
                    MessageBox.Show("Connexion acceptée par l'hôte.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    strTemp = ""
                    sbpConnection.Text = "Connecté !"
                    sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
            End Select
            If strTemp <> "" Then
             If strTemp.Substring(0,14) = "|FileSend|file" Then
             If Not strTemp.Substring(15,strTemp.IndexOf("~")-15) = txtNick.Text Then
             saveFile.Title = "Télécharger le fichier "+strTemp.Substring(strTemp.IndexOf("~")+1,strTemp.IndexOf("¦")-(strTemp.IndexOf("~")+1))
             saveFile.FileName = strTemp.Substring(strTemp.IndexOf("~")+1,strTemp.IndexOf("¦")-(strTemp.IndexOf("~")+1))
             saveFile.InitialDirectory = CurDir()+"Recus\"
             If saveFile.ShowDialog() = DialogResult.OK Then
             If Not System.IO.File.Exists(saveFile.FileName) Then System.IO.File.Create(saveFile.FileName).Close()
             System.IO.File.OpenWrite(saveFile.FileName).Write(ascii.GetBytes(strTemp.Substring(strTemp.IndexOf("¦")+1)),0, strTemp.Length-(strTemp.IndexOf("¦")+1))
             End If
             strTemp = ""
             End If
             Else
                txtAff.Text += strTemp & vbCrLf
                strTemp = ""
                End If
            End If
        End If
    End Sub

    Private Sub SocketSend(ByVal server As String, ByVal port As Integer, rqsType As String)
        If rqsType = "File" Then
         Dim RvFile As String()= sendFile.FileName.Split("\")
         Dim FileName = RvFile(RvFile.length-1)
         Request = "|FileSend|file$"+txtNick.Text+"~"+FileName+"¦"+System.IO.File.OpenText(sendFile.FileName).ReadToEnd()
         Dim bytesSent As [Byte]()= Encoding.UTF8.GetBytes(Request)
         Request = ""
         If txtNick.Text = "" Then
            MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Envoi annulé...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Exit Sub
            End If
         If Socket Is Nothing Then
            MessageBox.Show("Vous n'êtes pas connecté." & vbCrLf & "Envoi annulé...", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
         End If
         Try
         Socket.Send(bytesSent, bytesSent.Length, 0)
         Catch ex As Exception
         MessageBox.Show("Connexion coupée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
             Reset()
             Exit Sub
         End Try
        Else
        Request = txtNick.Text & " dit : " & vbCrLf & "  " & txtMessage.Text
        Dim ascii As Encoding = Encoding.UTF8
        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
        Request = ""
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Envoi annulé...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Exit Sub
        ElseIf txtMessage.Text = "" Then
            MessageBox.Show("Vous devez taper un message.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtMessage.Focus()
            Exit Sub
        End If

        If Socket Is Nothing Then
            MessageBox.Show("Vous n'êtes pas connecté." & vbCrLf & "Envoi annulé...", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        End If

        Try
            Socket.Send(bytesSent, bytesSent.Length, 0)
        Catch ex As Exception
            MessageBox.Show("Connexion coupée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Reset()
            Exit Sub
        End Try
        txtAff.Text += txtNick.Text & " dit : " & vbCrLf & "  " & txtMessage.Text & vbCrLf
        txtMessage.Text = ""
        End If
    End Sub

    Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
        If Socket Is Nothing Then
            MessageBox.Show("Non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            Exit Sub
        ElseIf txtMessage.Text = "" Then
            Exit Sub
        End If
        SocketSend(IP, 8157,"Normal")
    End Sub

    Private Sub txtAff_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtAff.TextChanged
       ' If txtAff.Lines.Length > 17 Then
           ' txtAff.Text = txtAff.Text.Remove(0, txtAff.Lines(0).Length + 2)
       ' End If
    End Sub

    Private Sub tmrNow_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrNow.Tick
        sbpDateSysteme.Text = Date.Now.ToString("dd/MM/yyyy")
        sbpHeureSysteme.Text = Date.Now.ToString("HH:mm:ss")
    End Sub

#Region "Partie Server"

    Private Sub btnServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnServer.Click
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez indiquer votre pseudo." & vbCrLf & "Hébergement annulé.", "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Exit Sub
        End If
        If btnServer.Text = "Héberger" Then
            btnServer.Text = "Arrêter d'héberger"
            gpbClient.Enabled = False
            TcpServer = New Net.Sockets.TcpListener(8157)
            TcpServer.Start()
            tmrWait.Enabled = True
            sbpConnection.Text = "En attente de connexion ..."
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
        Else
            btnServer.Text = "Héberger"
            gpbClient.Enabled = True
            tmrWait.Enabled = False
            tmrConnect.Enabled = False
            TcpServer.Stop()
            sbpConnection.Text = "Non connecté"
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
            If Socket Is Nothing Then
                Exit Sub
            Else
                If Socket.Connected = True Then
                    Request = ":connection:CLOSING"
                    Dim ascii As Encoding = Encoding.UTF8
                    Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                    Try
                        Socket.Send(bytesSent, bytesSent.Length, 0)
                        Socket.Close()
                        Socket = Nothing
                    Catch
                        Socket = Nothing
                        Exit Sub
                    End Try
                End If
            End If
            Exit Sub
        End If
    End Sub

    Private Sub tmrWait_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrWait.Tick
        If TcpServer.Pending = True Then
            tmrWait.Enabled = False
            Socket = TcpServer.AcceptSocket()
            TcpServer.Stop()
            If Socket.Connected = True Then
                If Socket.Available > 0 Then
                    strTemp = ""
                    bytes = Socket.Receive(Buffer, Buffer.Length, 0)
                    strTemp = strTemp + ascii.GetString(Buffer, 0, bytes)
                    Retour = MessageBox.Show("Souhaitez vous accepter la connexion en provenance de : " & IPAddress.Parse((CType(Socket.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString & " (" & strTemp & ")" & " ?", "Connexion", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                    strTemp = ""
                    If Retour = DialogResult.No Then
                        Request = ":connection:REFUSED"
                        Dim ascii As Encoding = Encoding.UTF8
                        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                        Try
                            Socket.Send(bytesSent, bytesSent.Length, 0)
                            Socket.Close()
                            Socket = Nothing
                        Catch
                            Socket = Nothing
                        End Try
                        TcpServer.Start()
                        tmrWait.Enabled = True
                        Socket = Nothing
                    Else
                        Request = ":connection:ACCEPTED"
                        Dim ascii As Encoding = Encoding.UTF8
                        Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                        Try
                            Socket.Send(bytesSent, bytesSent.Length, 0)
                        Catch
                        End Try
                        tmrConnect.Enabled = True
                        sbpConnection.Text = "Connecté !"
                        sbpConnection.Icon = New System.Drawing.Icon("TRFFC10A.ICO")
                    End If
                End If
            Else
                TcpServer.Start()
                tmrWait.Enabled = True
            End If
        End If
    End Sub

#End Region

#Region "Partie Client"

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        If btnConnect.Text = "Se connecter" Then
            If Connexion() = True Then
                tmrConnect.Enabled = True
                btnConnect.Text = "Se déconnecter"
                gpbServer.Enabled = False
                sbpConnection.Text = "En attente de l'acceptation de la connexion..."
                sbpConnection.Icon = New System.Drawing.Icon("TRFFC10B.ICO")
            Else
                Exit Sub
            End If
        Else
            btnConnect.Text = "Se connecter"
            gpbServer.Enabled = True
            tmrConnect.Enabled = False
            sbpConnection.Text = "Non connecté"
            sbpConnection.Icon = New System.Drawing.Icon("TRFFC10C.ICO")
            If Socket Is Nothing Then
                Exit Sub
            Else
                If Socket.Connected = True Then
                    Request = ":connection:CLOSING"
                    Dim ascii As Encoding = Encoding.UTF8
                    Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                    Try
                        Socket.Send(bytesSent, bytesSent.Length, 0)
                        Socket.Close()
                    Catch
                    End Try
                    Socket = Nothing
                End If
            End If
        End If
    End Sub

    Private Function Connexion() As Boolean
        If ValidationIP(txtIP.Text) = False Then
            MessageBox.Show("Adresse IP non valide !" & vbCrLf & "Connexion annulée.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Return False
            Exit Function
        Else
            IP = txtIP.Text
        End If
        If txtNick.Text = "" Then
            MessageBox.Show("Vous devez taper votre pseudo." & vbCrLf & "Connexion annulée...", "Pseudo", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            txtNick.Focus()
            Return False
            Exit Function
        End If
        Dim ascii As Encoding = Encoding.UTF8
        Dim Nick As String = txtNick.Text
        Dim nickSent As [Byte]() = ascii.GetBytes(Nick)
        Socket = ConnectSocket(IP, 8157)
        Try
            Socket.Send(nickSent, nickSent.Length, 0)
        Catch ex As Exception
            Return False
            Exit Function
        End Try
        Return True
    End Function

    Private Shared Function ConnectSocket(ByVal server As String, ByVal port As Integer) As Socket
        Dim Socket As Socket = Nothing
        Dim hostEntry As IPHostEntry = Nothing
        Try
            hostEntry = Dns.Resolve(server)
        Catch ex As Exception
            If InStr(ex.ToString, "No such host") >= 1 Then
                MessageBox.Show("Adresse IP non valide ou hôte non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End If
            MessageBox.Show(ex.ToString)
        End Try

        Dim address As IPAddress

        For Each address In hostEntry.AddressList
            Dim endPoint As New IPEndPoint(address, port)
            Dim tempSocket As New Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

            Try
                tempSocket.Connect(endPoint)
            Catch
                MessageBox.Show("Erreur lors de la connexion : hôte non joignable.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End Try

            If tempSocket.Connected Then
                Socket = tempSocket
                Exit For
            Else
                MessageBox.Show("Erreur lors de la connexion : non connecté.", "Connexion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Function
            End If

        Next address

        Return Socket
    End Function

    Public Function ValidationIP(ByVal strIP As String) As Boolean
        Try
            Dim Br1 As String, Br2 As String, Br3 As String, Br4 As String
            If InStr(strIP, ".") = 0 Then ValidationIP = False : Exit Function
            Br1 = Microsoft.VisualBasic.Strings.Mid(strIP, 1, InStr(strIP, ".") - 1)
            Br2 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + 2, (Len(strIP) - InStr(strIP, ".")) + 1)
            Br2 = Microsoft.VisualBasic.Strings.Left(Br2, InStr(Br2, ".") - 1)
            Br3 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + 3, Len(strIP))
            Br3 = Microsoft.VisualBasic.Strings.Left(Br3, InStr(Br3, ".") - 1)
            Br4 = Microsoft.VisualBasic.Strings.Mid(strIP, Len(Br1) + Len(Br2) + Len(Br3) + 4, Len(strIP))
            If IsNumeric(Br1) = False Or IsNumeric(Br2) = False Or IsNumeric(Br3) = False Or IsNumeric(Br4) = False Then ValidationIP = False : Exit Function
            If Not (CInt(Br1) >= 0 And CInt(Br1) <= 255) Or Not (CInt(Br2) >= 0 And CInt(Br2) <= 255) Or Not (CInt(Br3) >= 0 And CInt(Br3) <= 255) Or Not (CInt(Br4) >= 0 And CInt(Br4) <= 255) Then ValidationIP = False : Exit Function
            ValidationIP = True
            Exit Function
        Catch
            ValidationIP = False
        End Try
    End Function
#End Region

    Private Sub frmMain_Closing(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        tmrConnect.Enabled = False
        Dim sw As New StreamWriter("ipchat.ini", False)
        sw.WriteLine(txtNick.Text)
        sw.WriteLine(txtIP.Text)
        sw.Close()
        If Socket Is Nothing Then
        Else
            If Socket.Connected = True Then
                Request = ":connection:CLOSING"
                Dim ascii As Encoding = Encoding.UTF8
                Dim bytesSent As [Byte]() = ascii.GetBytes(Request)
                Try
                    Socket.Send(bytesSent, bytesSent.Length, 0)
                    Socket.Close()
                Catch
                    Exit Sub
                End Try
            End If
        End If
    End Sub

Private Sub sendFiler(sender As System.Object, e As System.EventArgs)
If sendFile.ShowDialog() = DialogResult.OK Then
SocketSend(IP, 8157,"File")
End If
End Sub

End Class
--------------------------------------------
la fonction sendFiler() est celle qui est activé lorsque le bouton est appuyé, et le paramètre supplémentaire de SocketSend permet de mettre l'en-tête qui indique un fichier.

Si vous mettez au début de votre texte ceci :
|FileSend|file
le programme interprétera cette demande comme suit:
|FileSend|file$[Nom de l'envoyeur(ET NON DU RECEVEUR)]~[Nom du fichier]¦[contenu du fichier]

Je ne verrais pourtant pas l'utilité de commencer un message avec |FileSend|file parfaitement écrit à moins de faire semblant que c'est un fichier.

Les fichiers sont limités aux fichiers ASCII et non BINAIRES sinon cela risque de générer une erreur.

Si vous voulez télécharger des fichiers, il faut avoir 2 nics différents car le programme s'assure de ne pas afficher le téléchargement à l'envoyeur par son nick...

signaler à un administrateur
Commentaire de OneHacker le 14/10/2005 21:50:36

Bravo ! Félicitations !

C'est exactement ce qu'il me faut !

Bonne continuation !

signaler à un administrateur
Commentaire de OneHacker le 14/10/2005 21:51:13

j'oublié ! 10/10 !

signaler à un administrateur
Commentaire de psycho81 le 01/03/2006 11:43:05

Je voudrai poser une question qui me pose problème depuis toujours pour les connections sur des postes distants. Voilà l'exemple que je voudrai pouvoir gérer :

Je suis dans un reseau local connecté à internet et je ne suis pas la passerelle.Je souhaite contacter un odinateur via Internet qui est lui aussi dans un reseau local connecté à internet et n'est pas la passerelle.

Marcher par IP n'est pas convenable car on tomberai sur l'IP de la passerelle. Comment faire sans passer par un serveur intermédiaure pour effectuer ce genre de liaison (un peu comme les programme de chat ou Emule :) )

Merci d'avance si vous connaissez la solution à mon probleme car je ne sais vraiment pas comment le solutionner.

PS : En coiurs réseau, on m'avait appris que ce serait une question de datagramme or je ne sais pas du tout comment construire de tel datagramme en VB.NET

signaler à un administrateur
Commentaire de TMONOD le 13/06/2008 12:00:03

Bonjour,
Très utile. Merci à toi.

signaler à un administrateur
Commentaire de Redman31100 le 28/10/2008 04:25:47

Je voulais savoir si tu utilises ton application chat sur internet et si oui quelle serait l'ip ?

Merci

signaler à un administrateur
Commentaire de team4ever le 29/01/2009 00:32:54

SVP tom le commentaire de ton code sources c'est interessant

signaler à un administrateur
Commentaire de team4ever le 29/01/2009 00:33:49

10/10

Ajouter un commentaire



Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,343 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.