none
chat via socket ajuda aqui? RRS feed

  • Pergunta

  • O servidor fica ON, o primeiro cliente entra, mas os demais clientes não conseguem se conectar, o servidor não deixa ;\

    Cliente :

    Imports System.Net.Sockets
    Imports System.Text
    
    Public Class Form1
        Dim clientSocket As New TcpClient()
        Dim serverStream As NetworkStream
        Dim lerDados As String
        Private Sub btnConectar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConectar.Click
            lerDados = "Conetado como Servidor ..."
            Mensagem()
            Try
                clientSocket.Connect("127.0.0.1", 8888)
                serverStream = clientSocket.GetStream()
                Dim outStream As Byte() = Encoding.ASCII.GetBytes(TextBox1)
                serverStream.Write(outStream, 0, outStream.Length)
                serverStream.Flush()
                'cria uma nova thread para enviar mensagens
                Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMensagem)
                ctThread.Start()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Sub
        Private Sub Mensagem()
            If Me.InvokeRequired Then
                Me.Invoke(New MethodInvoker(AddressOf Mensagem))
            Else
                TextBox2.Text = TextBox2.Text + Environment.NewLine + " >> " + lerDados
            End If
        End Sub
        Private Sub btnEnviarMensagem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnviarMensagem.Click
            Try
                Dim outStream As Byte() = Encoding.ASCII.GetBytes(TextBox3.Text + "$")
                serverStream.Write(outStream, 0, outStream.Length)
                serverStream.Flush()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Sub
        Private Sub getMensagem()
            'loop infinito
            While (True)
                Try
                    serverStream = clientSocket.GetStream()
                    Dim buffSize As Integer
                    Dim inStream(10024) As Byte
                    buffSize = clientSocket.ReceiveBufferSize
                    serverStream.Read(inStream, 0, buffSize)
                    Dim dadosRetornados As String = Encoding.ASCII.GetString(inStream)
                    lerDados = "" + dadosRetornados
                    Mensagem()
                Catch ex As Exception
                    MsgBox(ex.Message)
                    Exit Sub
                End Try
            End While
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        End Sub
    End Class

    Servidor:

    Imports System.Net
    Imports System.Text
    Imports System.Net.Sockets
    
    Module Module1
    
        Dim listaClientes As New Hashtable
        Sub Main()
            Dim enderecoLocal As IPAddress = IPAddress.Parse("127.0.0.1")
            Dim serverSocket As New TcpListener(enderecoLocal, 8888)
            Dim clientSocket As TcpClient = Nothing
            Dim contador As Integer
            serverSocket.Start()
            Mensagem("Servidor Chat Iniciado ....")
            contador = 0
            While (True)
                contador += 1
                clientSocket = serverSocket.AcceptTcpClient()
                Dim bytesFrom(10024) As Byte
                Dim dadosDoCliente As String
                Dim networkStream As NetworkStream = clientSocket.GetStream()
                networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
                dadosDoCliente = Encoding.ASCII.GetString(bytesFrom)
                dadosDoCliente = dadosDoCliente.Substring(0, dadosDoCliente.IndexOf("$"))
                listaClientes(dadosDoCliente) = clientSocket
                broadcast(dadosDoCliente + " Entrou ", dadosDoCliente, False)
                Mensagem(dadosDoCliente + " Entrou na Sala ")
                Dim cliente As New tratarCliente
                cliente.iniciaCliente(clientSocket, dadosDoCliente, listaClientes)
            End While
            clientSocket.Close()
            serverSocket.Stop()
            Mensagem("sair")
            Console.ReadLine()
        End Sub
        Sub Mensagem(ByVal texto As String)
            texto.Trim()
            Console.WriteLine(" >> " + texto)
        End Sub
        Private Sub broadcast(ByVal Mensagem As String, ByVal nomeUsuario As String, ByVal flag As Boolean)
            Dim Item As DictionaryEntry
            For Each Item In listaClientes
                Dim broadcastSocket As TcpClient
                broadcastSocket = CType(Item.Value, TcpClient)
                Try
                    Dim broadcastStream As NetworkStream = broadcastSocket.GetStream()
                    Dim broadcastBytes As [Byte]()
                    If flag = True Then
                        broadcastBytes = Encoding.ASCII.GetBytes(nomeUsuario + " diz : " + Mensagem)
                    Else
                        broadcastBytes = Encoding.ASCII.GetBytes(Mensagem)
                    End If
                    broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
                    broadcastStream.Flush()
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
            Next
        End Sub
        Public Class tratarCliente
            Dim clientSocket As TcpClient
            Dim clNo As String
            Dim listaClientes As Hashtable
            Public Sub iniciaCliente(ByVal inClientSocket As TcpClient, ByVal clineNo As String, ByVal cList As Hashtable)
                Me.clientSocket = inClientSocket
                Me.clNo = clineNo
                Me.listaClientes = cList
                Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
                ctThread.Start()
            End Sub
            Private Sub doChat()
                Dim contadorRequisicao As Integer
                Dim bytesFrom(10024) As Byte
                Dim dadosDoCliente As String
                Dim rContador As String
                contadorRequisicao = 0
                While (True)
                    Try
                        contadorRequisicao = contadorRequisicao + 1
                        Dim networkStream As NetworkStream = clientSocket.GetStream()
                        networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
                        dadosDoCliente = System.Text.Encoding.ASCII.GetString(bytesFrom)
                        dadosDoCliente = dadosDoCliente.Substring(0, dadosDoCliente.IndexOf("$"))
                        Mensagem("Cliente - " + clNo + " : " + dadosDoCliente)
                        rContador = Convert.ToString(contadorRequisicao)
                        broadcast(dadosDoCliente, clNo, True)
                    Catch ex As Exception
                        MsgBox(ex.ToString)
                    End Try
                End While
            End Sub
        End Class
    End Module

    sexta-feira, 7 de junho de 2013 23:41