dcsimg
Results 1 to 3 of 3

Thread: Multiple socket connections?

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2010
    Posts
    7

    Multiple socket connections?

    Hi again,

    OK here is some code I nicked from web and I have changed some things, it works but only accepting one client, how do I make this accept multiple clients?


    Code:
    Imports System.Net.Sockets
    Imports System.Text
    lass TCPSrv
        Shared Sub Main()
            ' Must listen on correct port- must be same as port client wants to connect on.
            Const portNumber As Integer = 29999
            Dim tcpListener As New TcpListener(portNumber)
            tcpListener.Start()
            Console.WriteLine("Waiting for connection...")
            Try
                'Accept the pending client connection and return a TcpClient initialized for communication. 
                Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()
                Console.WriteLine("Connection accepted.")
                Do While tcpClient.Connected = True
                    ' Get the stream
                    Dim networkStream As NetworkStream = tcpClient.GetStream()
                    ' Read the stream into a byte array
                    Dim bytes(tcpClient.ReceiveBufferSize) As Byte
                    Dim bytecount As Integer = networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
                    If bytecount > 0 Then
                        ' Return the data received from the client to the console.
                        Dim clientdata As String = Encoding.ASCII.GetString(bytes, 0, bytecount)
                        Console.WriteLine(clientdata)
                        Dim responseString As String = "OK"
                        Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(responseString)
                        networkStream.Write(sendBytes, 0, sendBytes.Length)
                        Console.WriteLine(responseString)
                        'Any communication with the remote client using the TcpClient can go here.
                        'Close TcpListener and TcpClient.
                    Else
                        tcpClient.Close()
                    End If
                Loop
                Console.WriteLine("Client disconnected")
        Catch e As Exception
            tcpListener.Stop()
            Console.WriteLine(e.ToString())
        End Try
        End Sub
    End Class

    Thanks and sorry for asking probably stupid questions!

    Steve

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    102,372

    Re: Multiple socket connections?

    When you call AcceptTcpClient, it will return a TcpClient when someone connects. If you want to accept another connection then you have to call AcceptTcpClient again.

    It's not really practical to use a Console application as a server like that. You might like to follow the CodeBank link in my signature and check out my Asynchronous TCP thread, which includes a WinForms server that accepts an unlimited number of connections. If you didn't want a UI then you'd create a Windows service, which is what a real server would likely be.

  3. #3

    Thread Starter
    New Member
    Join Date
    Mar 2010
    Posts
    7

    Re: Multiple socket connections?

    Thanks jmcilhinney

    Sorry for being thick but I have looked at your example a lot! and whilst I think I might understand it in a few years at the moment its well beyond me

    Even just using it as a DLL is beyond me as VB.NET is so new to me even the wording is taking some time to get used to. Now, if it was a matter of "Add TCPServer to your references, then pick up and drop the TCPServer control onto your form and away you go" I might have been able to do work with it he he.

    So I have gone back and looked at my TCPServer and your comments, I understand that a object is being created with "Dim tcpClient As TcpClient = tcpListener.AcceptTcpClient()" and that simply creating another would allow another connection, what I can't get my head round is how?

    Maybe its because its a console app and not a WinForms app, The console idea was not my choice just the code I found on the web that I could understand.

    OK current status is that I have thrown the code away and found some other code that says it will accept multiple connections however it again is console based, I created a Form1 and added a ListBox1 to show status, I have included the code and I know why it fails because my "Accept/Create Clients loop" is in the New method of Form1, but I cannot for the life of my think where it should be! my head is now spinning and I feel like going back to VB6 but I WONT!

    Code in the Form1.vb

    Code:
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Threading
    Imports System.Text
    
    Public Class Form1
    
        Public Sub New()
    
            ' This call is required by the designer.
            InitializeComponent()
    
            Dim serverSocket As New TcpListener(29999)
            Dim clientSocket As TcpClient
            Dim counter As Integer
    
            serverSocket.Start()
            Me.ListBox1.Items.Add("Server Started")
            counter = 0
            While (True)
                counter += 1
                clientSocket = serverSocket.AcceptTcpClient()
                Me.ListBox1.Items.Add("Client No:" + Convert.ToString(counter) + " started!")
                Dim client As New handleClinet
                client.startClient(clientSocket, Convert.ToString(counter))
            End While
    
            clientSocket.Close()
            serverSocket.Stop()
            Me.ListBox1.Items.Add("exit")
            Console.ReadLine()
        End Sub
    
    End Class

    Code in a TCPServ.vb

    Code:
        ByVal clineNo As String)
            Me.clientSocket = inClientSocket
            Me.clNo = clineNo
            Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
            ctThread.Start()
        End Sub
    
        Private Sub doChat()
            Dim requestCount As Integer
            Dim bytesFrom(10024) As Byte
            Dim dataFromClient As String
            Dim sendBytes As [Byte]()
            Dim serverResponse As String
            Dim rCount As String
            requestCount = 0
    
            While (True)
                Try
                    requestCount = requestCount + 1
                    Dim networkStream As NetworkStream = clientSocket.GetStream()
                    networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
                    dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
                    dataFromClient = _
                dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
                    Form1.ListBox1.Items.Add("From client-" + clNo + dataFromClient)
                    rCount = Convert.ToString(requestCount)
                    serverResponse = "Server to clinet(" + clNo + ") " + rCount
                    sendBytes = Encoding.ASCII.GetBytes(serverResponse)
                    networkStream.Write(sendBytes, 0, sendBytes.Length)
                    networkStream.Flush()
                    Form1.ListBox1.Items.Add(serverResponse)
                Catch ex As Exception
                    Form1.ListBox1.Items.Add(ex.ToString)
                End Try
    
            End While
    
        End Sub
    End Class
    Really sorry for being a newbie but as a older person I think it gets harder each time you learn a new language

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width