Page 4 of 5 FirstFirst 12345 LastLast
Results 121 to 160 of 163

Thread: [RESOLVED] [2008] Can I add a TCPClient Component

  1. #121
    New Member
    Join Date
    Apr 2009
    Posts
    3

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by Atheist View Post
    Well, the code in this thread will just give you a foundation to develop a client/server application. So if you need to be able to communicate with the computers in the "internet cafe" then you have some of the code to help you do so. However that would be just one small piece in building that kind of software. Disabling task managers and all that other non-networking stuff is another story.
    Alright, can you tell me which imports class should i use? I have discussed with my friend last night, they suggested UDP for the transport layer. TCP isn't appropriate?

  2. #122
    Hyperactive Member gooden's Avatar
    Join Date
    Dec 2006
    Location
    Portugal
    Posts
    274

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Hi Atheist

    I Have a little Question. If i want to send files is better to use a diferent protocol that connects between clients instead of sending The data From Client -> Server -> Other Client

    Am i Correct?


    The Future Is Always The Way To Live The Life

  3. #123
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Well..yeah sending entire files between two hosts with the server acting as an intermediate node will put alot of strain on the server. It could also become a bottleneck.
    Setting up a separate direct connection between the two hosts for the file transfer is a good idea.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  4. #124
    Hyperactive Member gooden's Avatar
    Join Date
    Dec 2006
    Location
    Portugal
    Posts
    274

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    So What i'm Making at this moment is using your TCP IP class to make a private message.

    So i will send a comand Like FILESEND|USER|NAMEFILE|SIZE|ETc.... and the in the other side i willl acept the conection Directly from user.

    So i don't have to use the server.

    =)

    Thanks For your help and great job =)


    The Future Is Always The Way To Live The Life

  5. #125
    New Member
    Join Date
    Jun 2009
    Posts
    1

    Resolved Re: [RESOLVED] [2008] Can I add a TCPClient Component

    You're a true hero Atheist.

  6. #126
    New Member
    Join Date
    Jul 2009
    Posts
    1

    Re: [2008] Can I add a TCPClient Component

    In your code what is "ConnectedClient"? Have you updated this code? Thanks for your help.

  7. #127
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    ConnectedClient is a class that represents a client connected to the server.
    I have not yet updated the code, sorry, I just keep forgetting it. As I look at it though...it wouldn't be a major update, but I'd rewrite the sending and receiving parts to utilize a BinaryReader/BinaryWriter instead, and thus remove the need for those pesky "delimiters".
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  8. #128
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    ConnectedClient is a class that represents a client connected to the server.
    I have not yet updated the code, sorry, I just keep forgetting it. As I look at it though...it wouldn't be a major update, but I'd rewrite the sending and receiving parts to utilize a BinaryReader/BinaryWriter instead, and thus remove the need for those pesky "delimiters".
    why not just create a public method for instance:
    Code:
    Public Sep_Char as String = "|:|" ' the |:| is the delimiter
    Public End_Char as String = ControlChars.cr
    now look how much easier it is:
    Code:
     
    Call SendMessage("packetname" & sep_char & "parse 1" & sep_char & "parse 2" & sep_char & "parse 3" & sep_char & "so forth" & end_char)
    there really shouldn't be any need of removing delimiters, makes it easier for me w/ them there .
    then you can create a data handling module:
    Code:
    Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    Call HandleData(Sender, Message)
    end Sub
    
    Sub HandleData(ByVal Index as ConnectedClient, ByVal msg as string)
    Dim Casestring as String
    Dim Parse() as String
    Parse = Split(Msg, SEP_CHAR)
    Casestring = Lcase(parse(0))
    
    if casestring = "packetname" then
    
    if parse(1) = "parse 1" then
    msgbox("ZOMFG! i got a packet!")
    end if
    
    if not parse(2) = "parse 2" then
    call sendmessage("packeterror" & end_char)
    exit sub
    end if
    
    exit sub
    end if
    end sub
    that right there is just a short cut guide for n00bs to Athiests chat program.


    On The Other Behalf I would like some help too:


    i'm new to all of the .NET framework multiplatform languages, i'm lagging behind w/ the rest of the old timers with VB6, VC++ 6 and etc. and i'm not used to object oriented programming ....sorry....here is my Question:

    is there a way i can make an arraylist instead of strings?

    i'm aiming to change this code:
    Code:
    Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    into something similar to this code:
    Code:
    Private Sub messageReceived(ByVal Sender as Integer, ByVal Message as String)
    Thanks in Return,
    Rydin


    EDIT:
    another thing i noticed was that when a client disconnects it fails to remove it and the server bugs too. if there is a fix for this thanks in return =D.

    Rydinophor
    Last edited by rydinophor; Jul 22nd, 2009 at 12:42 PM.

  9. #129
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by rydinophor View Post
    why not just create a public method for instance:
    Code:
    Public Sep_Char as String = "|:|" ' the |:| is the delimiter
    Public End_Char as String = ControlChars.cr
    now look how much easier it is:
    Code:
     
    Call SendMessage("packetname" & sep_char & "parse 1" & sep_char & "parse 2" & sep_char & "parse 3" & sep_char & "so forth" & end_char)
    there really shouldn't be any need of removing delimiters, makes it easier for me w/ them there .
    then you can create a data handling module:
    Code:
    Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    Call HandleData(Sender, Message)
    end Sub
    
    Sub HandleData(ByVal Index as ConnectedClient, ByVal msg as string)
    Dim Casestring as String
    Dim Parse() as String
    Parse = Split(Msg, SEP_CHAR)
    Casestring = Lcase(parse(0))
    
    if casestring = "packetname" then
    
    if parse(1) = "parse 1" then
    msgbox("ZOMFG! i got a packet!")
    end if
    
    if not parse(2) = "parse 2" then
    call sendmessage("packeterror" & end_char)
    exit sub
    end if
    
    exit sub
    end if
    end sub
    that right there is just a short cut guide for n00bs to Athiests chat program.
    Well, the thing about using character delimiters in text data is that what happens if the text that is to be sent contains the delimiter naturally? In other words, what if the message you'd like to get across to the receiver contains ControlChars.Cr in itself? The receiver would then treat the single message as two separate messages, split on that ControlChars.Cr occurance.
    By not using delimiters the text data can contain anything without any problems on the receiving end. It also makes it easier on the coding, as working with delimiters is a bit more tedious than using the BinaryWriter/BinaryReader approach.
    Quote Originally Posted by rydinophor View Post
    On The Other Behalf I would like some help too:


    i'm new to all of the .NET framework multiplatform languages, i'm lagging behind w/ the rest of the old timers with VB6, VC++ 6 and etc. and i'm not used to object oriented programming ....sorry....here is my Question:

    is there a way i can make an arraylist instead of strings?

    i'm aiming to change this code:
    Code:
    Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    into something similar to this code:
    Code:
    Private Sub messageReceived(ByVal Sender as Integer, ByVal Message as String)
    Thanks in Return,
    Rydin
    I'm not following, you'd like to use an ArrayList instead of a String where exactly? The only change I can see in your two lines is that you've changed ConnectedClient to Integer.
    Quote Originally Posted by rydinophor View Post
    EDIT:
    another thing i noticed was that when a client disconnects it fails to remove it and the server bugs too. if there is a fix for this thanks in return =D.

    Rydinophor
    Well...if the connection to the client is closed "abruptly" (client software crashes, cable is unplugged etc.), theres no way of avoiding an exception, so all you can do is to catch it, remove the client from your list of connected clients, and move on.
    If however the client disconnects gracefully, you would send a message to the server to let it know that this is the case, and close all connections.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  10. #130
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Smile Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by Atheist View Post
    I'm not following, you'd like to use an ArrayList instead of a String where exactly? The only change I can see in your two lines is that you've changed ConnectedClient to Integer.
    in other words is it possible to make it into an array of integers instead of using a class?

    Quote Originally Posted by Atheist View Post
    Well...if the connection to the client is closed "abruptly" (client software crashes, cable is unplugged etc.), theres no way of avoiding an exception, so all you can do is to catch it, remove the client from your list of connected clients, and move on.
    If however the client disconnects gracefully, you would send a message to the server to let it know that this is the case, and close all connections.
    i have that fixed, mans 2nd best friend did that:
    "On Error Resume Next"

    Quote Originally Posted by Atheist View Post
    Well, the thing about using character delimiters in text data is that what happens if the text that is to be sent contains the delimiter naturally? In other words, what if the message you'd like to get across to the receiver contains ControlChars.Cr in itself? The receiver would then treat the single message as two separate messages, split on that ControlChars.Cr occurance.
    By not using delimiters the text data can contain anything without any problems on the receiving end. It also makes it easier on the coding, as working with delimiters is a bit more tedious than using the BinaryWriter/BinaryReader approach.
    i wasn't born yesterday, for instance from what i showed above this packet:
    Call SendMessage("packetname" & sep_char & "parse 1" & sep_char & "parse 2" & end_char)
    here is what the full string is based off spliting from teh sep_char delmlimiters
    "packetname|:|parse 1|:|parse 2then w/e the controlchars.cr string is
    Last edited by rydinophor; Jul 23rd, 2009 at 12:17 PM.

  11. #131
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by rydinophor View Post
    in other words is it possible to make it into an array of integers instead of using a class?
    The class itself is what handles the communication with the client, so the best thing you could do, if you want each client to have a unique index, is to give the class an integer member and a public property for this, and give each client an incremented number as they connect.

    Quote Originally Posted by rydinophor View Post
    i have that fixed, mans 2nd best friend did that:
    "On Error Resume Next"
    On Error Resume Next is the worst way possible to handle exceptions I'm afraid. It's not so much error handling as it is, in fact, error ignoring.

    Quote Originally Posted by rydinophor View Post
    i wasn't born yesterday, for instance from what i showed above this packet:
    Call SendMessage("packetname" & sep_char & "parse 1" & sep_char & "parse 2" & end_char)
    here is what the full string is based off spliting from teh sep_char delmlimiters
    "packetname|:|parse 1|:|parse 2then w/e the controlchars.cr string is
    My apologies if I made it sound as if you where born yesterday, I was just presenting you with my reasons for choosing the "size-prefixed" variation over the "delimited" one.
    But still, what if "parse 1" in your example consisted of text that the user has written...and the user has written something consisting of either |:| or ControlChars.Cr. This could lead to unexpected results, and even security problems.
    When I say security problems; Take this scenario into consideration...
    Perhaps you have it so that when a client sends a message to someone else, it sends the following: MESSAGE|:|MyNickName|:|ReciepentsNickName|:|MyMessage
    Now...what if I, as a user of your application, writes a message to someone, but in my actual message I write ControlChars.Cr first, and then MESSAGE|:|SomeOneElsesNickName|:|ReciepentsNickName|:|MyMessage.
    What would happen if that was sent? Of course, one could argue that you shouldnt let the user write |:| or ControlChars.Cr in the message in the first place, but why restrict the user to avoid unpexpected behaviour, when a better design in the first place could?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  12. #132
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Smile Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by Atheist View Post
    The class itself is what handles the communication with the client, so the best thing you could do, if you want each client to have a unique index, is to give the class an integer member and a public property for this, and give each client an incremented number as they connect.
    i got that array to work now i need to get it to where i can send data to the specified integer member:
    Code:
       
    Private mIndex As Integer
    Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As Form1, ByVal IsIndex As Integer)
            mParentForm = parentForm
            mClient = client
    mIndex = IsIndex
            mIndex = Index
            readThread = New System.Threading.Thread(AddressOf doRead)
            readThread.IsBackground = True
            readThread.Start()
        End Sub
        Public Property Index() As Integer
            Get
                Return mIndex
            End Get
            Set(ByVal value As Integer)
                mIndex = Index
            End Set
        End Property
    Form1:
    Code:
        Private Sub doListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                For i As Integer = 1 To 10
                    incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    
                    Dim connClient As New ConnectedClient(incomingClient, Me, i)
    
                    'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
                    AddHandler connClient.dataReceived, AddressOf Me.messageReceived
                    'clients.Add(connClient) 'Adds the connected client to the list of connected clients.
                    clients.Add(connClient)
                Next
            Loop
        End Sub
    i also have found this and never seen this command before:
    Code:
    Dim index As Integer = clients.IndexOf(client)
    what will this do?
    have any ideas?

    Quote Originally Posted by Atheist View Post
    On Error Resume Next is the worst way possible to handle exceptions I'm afraid. It's not so much error handling as it is, in fact, error ignoring.
    Fixed Also, I used the Try and Catch Method and found the error.

    Quote Originally Posted by Atheist View Post
    My apologies if I made it sound as if you where born yesterday, I was just presenting you with my reasons for choosing the "size-prefixed" variation over the "delimited" one.
    But still, what if "parse 1" in your example consisted of text that the user has written...and the user has written something consisting of either |:| or ControlChars.Cr. This could lead to unexpected results, and even security problems.
    When I say security problems; Take this scenario into consideration...
    Perhaps you have it so that when a client sends a message to someone else, it sends the following: MESSAGE|:|MyNickName|:|ReciepentsNickName|:|MyMessage
    Now...what if I, as a user of your application, writes a message to someone, but in my actual message I write ControlChars.Cr first, and then MESSAGE|:|SomeOneElsesNickName|:|ReciepentsNickName|:|MyMessage.
    What would happen if that was sent? Of course, one could argue that you shouldnt let the user write |:| or ControlChars.Cr in the message in the first place, but why restrict the user to avoid unpexpected behaviour, when a better design in the first place could?
    Fixed, Thanks =)


    Thanks In Return,
    Rydinophor
    Last edited by rydinophor; Jul 24th, 2009 at 12:17 PM.

  13. #133
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by rydinophor View Post
    i got that array to work now i need to get it to where i can send data to the specified integer member:
    Code:
       
    Private mIndex As Integer
    Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As Form1, ByVal IsIndex As Integer)
            mParentForm = parentForm
            mClient = client
    mIndex = IsIndex
            mIndex = Index
            readThread = New System.Threading.Thread(AddressOf doRead)
            readThread.IsBackground = True
            readThread.Start()
        End Sub
        Public Property Index() As Integer
            Get
                Return mIndex
            End Get
            Set(ByVal value As Integer)
                mIndex = Index
            End Set
        End Property
    Form1:
    Code:
        Private Sub doListen()
            Dim incomingClient As System.Net.Sockets.TcpClient
            Do
                For i As Integer = 1 To 10
                    incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    
                    Dim connClient As New ConnectedClient(incomingClient, Me, i)
    
                    'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
                    AddHandler connClient.dataReceived, AddressOf Me.messageReceived
                    'clients.Add(connClient) 'Adds the connected client to the list of connected clients.
                    clients.Add(connClient)
                Next
            Loop
        End Sub
    i also have found this and never seen this command before:
    Code:
    Dim index As Integer = clients.IndexOf(client)
    what will this do?
    have any ideas?
    That IndexOf call will return the index of the client in the clients collection... I suppose you could actually make use of that index altogether and forget about giving the client itself an extra property, like I said in my last post.

    Quote Originally Posted by rydinophor View Post
    Fixed Also, I used the Try and Catch Method and found the error.
    Great
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  14. #134
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by Atheist View Post
    That IndexOf call will return the index of the client in the clients collection... I suppose you could actually make use of that index altogether and forget about giving the client itself an extra property, like I said in my last post.
    i have that covered thanks . now the only problem is changing it back and i just figure that out too:
    Code:
     Dim Sender As ConnectedClient = clients.Item(Index)
            Sender.SendMessage(Message)
    the only problem is i can't call that sub(in frmserver class) from a module(modtcpserver) can you help me out on this one?

  15. #135
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Do you mean that you can not access the clients object from the module?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  16. #136
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    here let me show you what i'm trying to do and its not working:
    in Module modServerTCP:
    Code:
        Sub SendDataTo(ByVal Index As Integer, ByVal Data As String)
            Call frmServer.SendDataTos(Index, Data)
        End Sub
    in Public Class frmServer:
    Code:
        Sub SendDataTos(ByVal Index As Integer, ByVal Message As String)
            MsgBox("this is what i'm trying to access!")
            Dim Sender As ConnectedClient = clients.Item(Index)
            Sender.SendMessage(Message)
    End Sub
    both of these are in the server.

  17. #137
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    You cant access it at all? I think it should be public by default but try adding the Public modifier infront of Sub.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  18. #138
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    nope still didn't work i added public in front of Sub SendDataTos(ByVal Index As Integer, ByVal Message As String)

  19. #139
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    In what way can you not access it? I am under the impression that frmServer is the name of your class, and that you are specifying 'frmServer' because you're using the forms default instance. If this is not the case you'll have some more problems.
    But lets start with the question; In what way can you not access it? Does it not appear in the intellisense? Do you get an error when trying to call it?
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  20. #140
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    nvm i got it something was messing up the packets from behind the calls.
    Thanks Again,
    Rydinophor

  21. #141
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    sorry for the double post, but i really don't like threaded sockets, can you show an example of Async Sockets? i get this error when coding and the try and catch doesn't even work on it:
    Code:
    The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
    Thanks In Return,
    Rydinophor

  22. #142
    Raging swede Atheist's Avatar
    Join Date
    Aug 2005
    Location
    Sweden
    Posts
    8,018

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    I can't give you an example right now as I'm at work; but show me what you've got and we could work from that.
    Rate posts that helped you. I do not reply to PM's with coding questions.
    How to Get Your Questions Answered
    Current project: tunaOS
    Me on.. BitBucket, Google Code, Github (pretty empty)

  23. #143
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    sorry about a no reply for 2 days my mind was on work and offset to java, i used a few async tuts and managed to get it too work, the only prob is when my client disconnects the server absolutely rejects all client requests

  24. #144
    Addicted Member
    Join Date
    Jan 2006
    Posts
    246

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Code:
        Public Sub Senddata(ByVal msg As String)
            Dim sw As New IO.StreamWriter(frmMain.client.GetStream)
            Try
                sw.Write(msg)
                sw.Flush()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
    This senddata sub works fine from frmMain, but I have all my functions and subs inside of a module. I tried creating the sub above so I could put this function inside my module as well, but I keep getting the following error:

    "Object reference not set to an instance of an object"

    I cannot for the life of me figure out what I am missing. Can anyone share some brain food?

    Thank you for your time.

  25. #145
    Addicted Member
    Join Date
    Jan 2006
    Posts
    246

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by rydinophor View Post
    sorry for the double post, but i really don't like threaded sockets, can you show an example of Async Sockets? i get this error when coding and the try and catch doesn't even work on it:
    Code:
    The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone).
    Thanks In Return,
    Rydinophor
    First off sorry for the double post. I also am running into this problem. Would you mind saying how you fixed it?

    thanks!

  26. #146
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    I never managed to fix the issue, instead i switched to asynchronous sockets.

    I don't know where to start but I've been looking for something like this for months, I took a look at atheists simple chat program with threaded sockets but no sooner then i tryed i found out that Asynchronous Sockets run 20x faster then Threaded sockets, So I would like to contribute to the community as well and post my Chat Example Program In which you can send data back and forth to specific clients:

    TCP Client Side:
    In Form1:
    Code:
    '
    'C# Network Programming 
    'by Richard Blum
    '
    'Publisher: Sybex 
    'ISBN: 0782141765
    '
    
    
    Imports System
    Imports System.Drawing
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text
    Imports System.Windows.Forms
    
    
    Public Class AsyncTcpClient
        Inherits Form
        Private newText As TextBox
        Private conStatus As TextBox
        Private results As ListBox
        Private client As Socket
        Private data As Byte() = New Byte(1023) {}
        Private sizes As Integer = 1024
    
        Public Sub New()
            Text = "Asynchronous TCP Client"
            Size = New Size(400, 380)
    
            Dim label1 As New Label()
            label1.Parent = Me
            label1.Text = "Enter text string:"
            label1.AutoSize = True
            label1.Location = New Point(10, 30)
    
            newText = New TextBox()
            newText.Parent = Me
            newText.Size = New Size(200, 2 * Font.Height)
            newText.Location = New Point(10, 55)
    
            results = New ListBox()
            results.Parent = Me
            results.Location = New Point(10, 85)
            results.Size = New Size(360, 18 * Font.Height)
    
            Dim label2 As New Label()
            label2.Parent = Me
            label2.Text = "Connection Status:"
            label2.AutoSize = True
            label2.Location = New Point(10, 330)
    
            conStatus = New TextBox()
            conStatus.Parent = Me
            SetConnectionLabelText("Disconnected")
            conStatus.Size = New Size(200, 2 * Font.Height)
            conStatus.Location = New Point(110, 325)
    
            Dim sendit As New Button()
            sendit.Parent = Me
            sendit.Text = "Send"
            sendit.Location = New Point(220, 52)
            sendit.Size = New Size(5 * Font.Height, 2 * Font.Height)
            AddHandler sendit.Click, AddressOf ButtonSendOnClick
    
            Dim connect As New Button()
            connect.Parent = Me
            connect.Text = "Connect"
            connect.Location = New Point(295, 20)
            connect.Size = New Size(6 * Font.Height, 2 * Font.Height)
            AddHandler connect.Click, AddressOf ButtonConnectOnClick
    
            Dim discon As New Button()
            discon.Parent = Me
            discon.Text = "Disconnect"
            discon.Location = New Point(295, 52)
            discon.Size = New Size(6 * Font.Height, 2 * Font.Height)
            AddHandler discon.Click, AddressOf ButtonDisconOnClick
        End Sub
    
        Private Sub ButtonConnectOnClick(ByVal obj As Object, ByVal ea As EventArgs)
            SetConnectionLabelText("Connecting...")
            Dim newsock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim iep As New IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050)
            newsock.BeginConnect(iep, New AsyncCallback(AddressOf Connected), newsock)
        End Sub
    
        Private Sub ButtonSendOnClick(ByVal obj As Object, ByVal ea As EventArgs)
            Dim message As Byte() = Encoding.ASCII.GetBytes(newText.Text)
            newText.Clear()
            client.BeginSend(message, 0, message.Length, SocketFlags.None, New AsyncCallback(AddressOf SendData), client)
        End Sub
    
        Private Sub ButtonDisconOnClick(ByVal obj As Object, ByVal ea As EventArgs)
            client.Close()
            SetConnectionLabelText("Disconnected")
        End Sub
    
        Private Sub Connected(ByVal iar As IAsyncResult)
            client = DirectCast(iar.AsyncState, Socket)
            Try
                client.EndConnect(iar)
                SetConnectionLabelText("Connected to: " & client.RemoteEndPoint.ToString())
                client.BeginReceive(data, 0, sizes, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), client)
            Catch generatedExceptionName As SocketException
                SetConnectionLabelText("Error connecting")
            End Try
        End Sub
        Private Delegate Sub StringDelegate(ByVal text As String)
    
        Private Sub SetConnectionLabelText(ByVal text As String)
            If conStatus.InvokeRequired Then
                Me.Invoke(New StringDelegate(AddressOf SetConnectionLabelText), text)
            Else
                conStatus.Text = text
            End If
        End Sub
        Private Sub ReceiveData(ByVal iar As IAsyncResult)
            Dim remote As Socket = DirectCast(iar.AsyncState, Socket)
            Dim recv As Integer = remote.EndReceive(iar)
            Dim stringData As String = Encoding.ASCII.GetString(data, 0, recv)
            SetText(stringData & vbCrLf)
        End Sub
        Private Delegate Sub StringDel(ByVal text As String)
        Private Sub SetText(ByVal text As String)
            If results.InvokeRequired Then
                Me.Invoke(New StringDel(AddressOf SetText), text)
            Else
                results.Text = text
            End If
        End Sub
    
        Private Sub SendData(ByVal iar As IAsyncResult)
            Dim remote As Socket = DirectCast(iar.AsyncState, Socket)
            Dim sent As Integer = remote.EndSend(iar)
            remote.BeginReceive(data, 0, sizes, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), remote)
        End Sub
    
        Public Shared Sub Main()
            Application.Run(New AsyncTcpClient())
        End Sub
    End Class
    Server Side:
    In Form1:
    Code:
    Imports System.Net.Sockets
    Imports System.Net
    Imports System.Text
    Public Class Form1
        Public SEP_CHAR As String = "|"
        Private data As Byte() = New Byte(1023) {}
        Private sizes As Integer = 1024
        Private server As Socket
        Dim ClientList As New List(Of Socket)
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            server = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            Dim End_Point As New IPEndPoint(IPAddress.Any, 9050)
            server.Bind(End_Point)
            server.Listen(5)
            server.BeginAccept(New AsyncCallback(AddressOf AcceptConn), server)
        End Sub
        Private Sub AcceptConn(ByVal iar As IAsyncResult)
            Dim oldserver As Socket = DirectCast(iar.AsyncState, Socket)
            ' Client = DirectCast(iar.AsyncState, Socket)
            Dim client As Socket = oldserver.EndAccept(iar) '
            ClientList.Add(client)
            SetConnectionLabelText("Connected to: ") '& Client.RemoteEndPoint.ToString)
            Dim stringData As String = "Welcome to my server"
            Dim message1 As Byte() = Encoding.ASCII.GetBytes(stringData)
            ClientList(ClientList.IndexOf(client)).BeginSend(message1, 0, message1.Length, SocketFlags.None, New AsyncCallback(AddressOf SendData), ClientList.Item(ClientList.IndexOf(client)))
        End Sub
        Private Delegate Sub StringDelegate(ByVal text As String)
    
        Private Sub SetConnectionLabelText(ByVal text As String)
            If TextBox1.InvokeRequired Then
                Me.Invoke(New StringDelegate(AddressOf SetConnectionLabelText), TextBox1.Text & text & vbCrLf)
            Else
                TextBox1.Text = text
            End If
        End Sub
        Private Sub SendData(ByVal iar As IAsyncResult)
            'w/e that was was really strange it feels like 2012 december 21 right now lol
            Dim sent As Integer = ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))).EndSend(iar) 'hmm
            ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))).BeginReceive(data, 0, sizes, SocketFlags.None, New AsyncCallback(AddressOf ReceiveData), ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))))
        End Sub
    
        Private Sub ReceiveData(ByVal iar As IAsyncResult)
            On Error Resume Next
            Dim recv As Integer
            recv = ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))).EndReceive(iar)
            If recv = 0 Then
                ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))).Close()
                SetConnectionLabelText("Waiting for client...")
                server.BeginAccept(New AsyncCallback(AddressOf AcceptConn), server)
                Exit Sub
            End If
            Dim receivedData As String = Encoding.ASCII.GetString(data, 0, recv)
            ' Call SetConnectionLabelText(TextBox1.Text & receivedData & vbNewLine)
            Call HandleData(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket)), receivedData)
            Dim message2 As Byte() = Encoding.ASCII.GetBytes(receivedData)
            ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))).BeginSend(message2, 0, message2.Length, SocketFlags.None, New AsyncCallback(AddressOf SendData), ClientList.Item(ClientList.IndexOf(DirectCast(iar.AsyncState, Socket))))
        End Sub
        Sub HandleData(ByVal Index As Integer, ByVal Data As String)
            Dim CaseString() As String = Data.Split("|"c) 'Split the message on each | and place in the string array.
            Dim Parse() As String = Data.Split("|"c)
            Select Case CaseString(0)
                Case "bob"
                    If Parse(1) = "yes" Then
                        SetConnectionLabelText("ZOMFG! The Case Worked!")
                        Exit Sub
                    End If
            End Select
        End Sub
    End Class
    Credit Goes To Athiest For A Few Snippets and http://www.java2s.com/Code/CSharp/Ne...cTcpServer.htm
    Last edited by rydinophor; Sep 17th, 2009 at 09:57 PM.

  27. #147
    Junior Member rydinophor's Avatar
    Join Date
    Jul 2009
    Location
    Missouri, USA
    Posts
    18

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Sorry For The Double Post but is there anyway of accessing the forms controls from another module? I tried adding some text to textbox1 in form1 from modtcpinit and its not working very well, any suggestions?

    Thanks In Return,
    Rydinophor

  28. #148
    New Member
    Join Date
    Sep 2009
    Posts
    4

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    hey Atheist, thanks for the great example code. I've started to use it and have noticed that when i disconnect, and send a "DISCONNECT" message, the client gets removed from the list but from that point onwards, the program starts taking up most of my CPU cycles - doRead is looping. Is there anything I can do to stop this?

    thanks in advance

  29. #149
    Hyperactive Member
    Join Date
    Mar 2005
    Posts
    312

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    This is my version of the code but its not working for me

    Server

    Code:
    Imports System.Net.Sockets
    Imports System.Net
    Imports System.IO
    
    Public Class Form1
        Dim myListener As TcpListener
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            myListener = New TcpListener(Net.IPAddress.Any, 8000)
            myListener.Start()
            Button1.Enabled = False
            lblConnect.Text = "Connected to Port No 8000"
            DoListen()
        End Sub
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub DoListen()
    
            'This is the sub that does all the actual "listening". Its an endless loop that calls the AcceptTcpClient method over and over.
    
            'If there is no connecting TcpClient, it will raise an exception but we will ignore this by catching it in a try statement and doing nothing with it.
    
            'On the other hand, If a client has connected, it proceeds to the next line and a streamreader reads the incoming stream and shows it in a messagebox.
            Dim sr As IO.StreamReader
    
            Do
    
                Try
                    Dim client As Net.Sockets.TcpClient = myListener.AcceptTcpClient
    
                    sr = New IO.StreamReader(client.GetStream)
                    MessageBox.Show(sr.ReadToEnd)
    
                    sr.Close()
    
                Catch
    
                End Try
            Loop
    
        End Sub
    
        Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
            End
        End Sub
    End Class

    Client

    Code:
    Imports System.IO
    Imports System.Net
    Imports System.Net.Sockets
    
    Public Class Form1
        Private client As System.Net.Sockets.TcpClient
        Private Const BYTES_TO_READ As Integer = 255
        Private readBuffer(BYTES_TO_READ) As Byte
    
        Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        End Sub
    
        Private Sub messageReceived(ByVal message As String)
            MessageBox.Show(message)
        End Sub
    
    
    
        Private Sub SendMessage(ByVal msg As String)
            Dim sw As IO.StreamWriter
            Try
                sw = New IO.StreamWriter(client.GetStream)
                sw.Write(msg)
                sw.Flush()
            Catch ex As Exception
                MessageBox.Show(ex.ToString)
            End Try
        End Sub
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            client = New System.Net.Sockets.TcpClient("localhost", 8000)
            client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing)
        End Sub
    
        Private Sub doRead(ByVal ar As System.IAsyncResult)
            Dim totalRead As Integer
            Try
                totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
            Catch ex As Exception
                'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
                'to this client and remove it from the list of connected clients.
            End Try
    
            If totalRead > 0 Then
                'the readBuffer array will contain everything read from the client.
                Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
                messageReceived(receivedString)
            End If
    
            Try
                client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
            Catch ex As Exception
                'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
                'to this client and remove it from the list of connected clients.
            End Try
        End Sub
    
        Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
            SendMessage("Hi there")
        End Sub
    End Class
    Can anybody help me out with this?

  30. #150
    Member adamj12b's Avatar
    Join Date
    Jan 2005
    Location
    Charlton Mass
    Posts
    51

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    What is the error you are getting?

    -Adam

  31. #151
    Member
    Join Date
    Jan 2010
    Posts
    46

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    what if you want to stop listener? I mean if the user wants to change username or port?

    This is where you start to listen from clients:

    listener = New TcpListener(IPAddress.Any, txtPort.Text)
    listener.Start() 'Start listening.
    listenThread = New Thread(AddressOf DoListen)
    listenThread.IsBackground = True
    listenThread.Start()

    And here's the DoListen

    Private Sub DoListen()
    Dim incomingClient As System.Net.Sockets.TcpClient
    Do
    incomingClient = listener.AcceptTcpClient
    Dim connClient As New ConnectedClient(incomingClient, Me)
    AddHandler connClient.dataReceived, AddressOf Me.MessageReceived
    clients.Add(connClient) 'Adds the connected client to the list of connected clients.
    Me.MessageReceived
    Loop
    End Sub

    How do you stop listener? I tried doing this but I always get an error:

    listener.Stop()
    listenThread.Abort()

  32. #152
    Member
    Join Date
    Jan 2010
    Posts
    46

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    oh I already solved my first question well I have another one:

    this code to connects to server:

    client = New TcpClient(txtIP.Text, txtPort.Text)
    client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf DoRead, Nothing)
    SendMessage("/CONNECT|" & Label25.Text)

    How do I check if the TcpListener is available?

    I get this error when I run it without a server

    "No connection could be made because the target machine actively refused it 127.0.0.1:43000"

    What if the client is running then suddenly the server restarts?

  33. #153
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    993

    Re: [2008] Can I add a TCPClient Component

    Quote Originally Posted by Atheist View Post
    In the specific post by me that you linked too, there is only code for the server side. But in the same thread, I've got examples for the client side aswell.
    Anyway, I'll create one more example..

    Server side:
    Form:
    VB.Net Code:
    1. Public Class Form1
    2.     Private listener As System.Net.Sockets.TcpListener
    3.     Private listenThread As System.Threading.Thread
    4.  
    5.     Private clients As New List(Of ConnectedClient) 'This list will store all connected clients.
    6.  
    7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         listener = New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 43001) 'The TcpListener will listen for incoming connections at port 43001
    9.         listener.Start() 'Start listening.
    10.         listenThread = New System.Threading.Thread(AddressOf doListen) 'This thread will run the doListen method
    11.         listenThread.IsBackground = True 'Since we dont want this thread to keep on running after the application closes, we set isBackground to true.
    12.         listenThread.Start() 'Start executing doListen on the worker thread.
    13.     End Sub
    14.  
    15.     Private Sub doListen()
    16.         Dim incomingClient As System.Net.Sockets.TcpClient
    17.         Do
    18.             incomingClient = listener.AcceptTcpClient 'Accept the incoming connection. This is a blocking method so execution will halt here until someone tries to connect.
    19.             Dim connClient As New ConnectedClient(incomingClient, Me) 'Create a new instance of ConnectedClient (check its constructor to see whats happening now).
    20.             AddHandler connClient.dataReceived, AddressOf Me.messageReceived
    21.             clients.Add(connClient) 'Adds the connected client to the list of connected clients.
    22.  
    23.         Loop
    24.     End Sub
    25.  
    26.     Public Sub removeClient(ByVal client As ConnectedClient)
    27.         If clients.Contains(client) Then
    28.             clients.Remove(client)
    29.         End If
    30.     End Sub
    31.  
    32.     Private Sub messageReceived(ByVal sender As ConnectedClient, ByVal message As String)
    33.         'A message has been received from one of the clients.
    34.         'To determine who its from, use the sender object.
    35.         'sender.SendMessage can be used to reply to the sender.
    36.  
    37.         Dim data() As String = message.Split("|"c) 'Split the message on each | and place in the string array.
    38.         Select Case data(0)
    39.             Case "CONNECT"
    40.                 'We use GetClientByName to make sure no one else is using this username.
    41.                 'It will return Nothing if the username is free.
    42.                 'Since the client sent the message in this format: CONNECT|UserName, the username will be in the array on index 1.
    43.                 If GetClientByName(data(1)) Is Nothing Then
    44.                     'The username is not taken, we can safely assign it to the sender.
    45.                     sender.Username = data(1)
    46.                 End If
    47.             Case "DISCONNECT"
    48.                 removeClient(sender)
    49.         End Select
    50.  
    51.     End Sub
    52.  
    53.     Private Function GetClientByName(ByVal name As String) As ConnectedClient
    54.         For Each cc As ConnectedClient In clients
    55.             If cc.Username = name Then
    56.                 Return cc 'client found, return it.
    57.             End If
    58.         Next
    59.         'If we've reached this part of the method, there is no client by that name
    60.         Return Nothing
    61.     End Function
    62. End Class
    ConnectedClient class:
    VB.Net Code:
    1. Public Class ConnectedClient
    2.     Private mClient As System.Net.Sockets.TcpClient
    3.  
    4.     Private mUsername As String
    5.     Private mParentForm As Form1
    6.     Private readThread As System.Threading.Thread
    7.     Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
    8.  
    9.     Public Event dataReceived(ByVal sender As ConnectedClient, ByVal message As String)
    10.  
    11.     Sub New(ByVal client As System.Net.Sockets.TcpClient, ByVal parentForm As Form1)
    12.         mParentForm = parentForm
    13.         mClient = client
    14.  
    15.         readThread = New System.Threading.Thread(AddressOf doRead)
    16.         readThread.IsBackground = True
    17.         readThread.Start()
    18.     End Sub
    19.  
    20.     Public Property Username() As String
    21.         Get
    22.             Return mUsername
    23.         End Get
    24.         Set(ByVal value As String)
    25.             mUsername = value
    26.         End Set
    27.     End Property
    28.  
    29.     Private Sub doRead()
    30.         Const BYTES_TO_READ As Integer = 255
    31.         Dim readBuffer(BYTES_TO_READ) As Byte
    32.         Dim bytesRead As Integer
    33.         Dim sBuilder As New System.Text.StringBuilder
    34.         Do
    35.             bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
    36.             If (bytesRead > 0) Then
    37.                 Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
    38.                 If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
    39.  
    40.                     Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
    41.  
    42.                     'The first element in the subMessages string array must be the last part of the current message.
    43.                     'So we append it to the StringBuilder and raise the dataReceived event
    44.                     sBuilder.Append(subMessages(0))
    45.                     RaiseEvent dataReceived(Me, sBuilder.ToString)
    46.                     sBuilder = New System.Text.StringBuilder
    47.  
    48.                     'If there are only 2 elements in the array, we know that the second one is an incomplete message,
    49.                     'though if there are more then two then every element inbetween the first and the last are complete messages:
    50.                     If subMessages.Length = 2 Then
    51.                         sBuilder.Append(subMessages(1))
    52.                     Else
    53.                         For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
    54.                             RaiseEvent dataReceived(Me, subMessages(i))
    55.                         Next
    56.                         sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
    57.                     End If
    58.                 Else
    59.  
    60.                     'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
    61.                     sBuilder.Append(message)
    62.                 End If
    63.             End If
    64.         Loop
    65.     End Sub
    66.  
    67.     Public Sub SendMessage(ByVal msg As String)
    68.         Dim sw As IO.StreamWriter
    69.         Try
    70.             SyncLock mClient.GetStream
    71.                 sw = New IO.StreamWriter(mClient.GetStream) 'Create a new streamwriter that will be writing directly to the networkstream.
    72.                 sw.Write(msg)
    73.                 sw.Flush()
    74.             End SyncLock
    75.         Catch ex As Exception
    76.             MessageBox.Show(ex.ToString)
    77.         End Try
    78.         'As opposed to writing to a file, we DONT call close on the streamwriter, since we dont want to close the stream.
    79.     End Sub
    80.  
    81. End Class

    Client Side:
    Form:
    VB.Net Code:
    1. Public Class Form1
    2.     Private client As System.Net.Sockets.TcpClient
    3.  
    4.     Private Const BYTES_TO_READ As Integer = 255
    5.     Private readBuffer(BYTES_TO_READ) As Byte
    6.  
    7.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    8.         client = New System.Net.Sockets.TcpClient("localhost", 43001)
    9.         client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing)
    10.     End Sub
    11.  
    12.     Private Sub doRead(ByVal ar As System.IAsyncResult)
    13.         Dim totalRead As Integer
    14.         Try
    15.             totalRead = client.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
    16.         Catch ex As Exception
    17.             'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
    18.             'to this client and remove it from the list of connected clients.
    19.         End Try
    20.  
    21.             If totalRead > 0 Then
    22.                 'the readBuffer array will contain everything read from the client.
    23.                 Dim receivedString As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, totalRead)
    24.                 messageReceived(receivedString)
    25.             End If
    26.  
    27.             Try
    28.                 client.GetStream.BeginRead(readBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
    29.             Catch ex As Exception
    30.                 'The underlying socket have probably been closed OR an error has occured whilst trying to access it, either way, this is where you should remove close all eventuall connections
    31.                 'to this client and remove it from the list of connected clients.
    32.             End Try
    33.     End Sub
    34.  
    35.     Private Sub messageReceived(ByVal message As String)
    36.         MessageBox.Show(message)
    37.     End Sub
    38.  
    39.  
    40.  
    41.     Private Sub SendMessage(ByVal msg As String)
    42.         Dim sw As IO.StreamWriter
    43.         Try
    44.             sw = New IO.StreamWriter(client.GetStream)
    45.             sw.Write(msg)
    46.             sw.Flush()
    47.         Catch ex As Exception
    48.             MessageBox.Show(ex.ToString)
    49.         End Try
    50.     End Sub
    51. End Class
    You need to add more exception handling and possibly some SyncLocks upon accessing the different Streams. There are also some important things that I've left out, such as removing a client from the list of connected client upon disconnection.
    I've tried to put some comments in the code but dont hesitate to look the different methods/classes up on MSDN.

    Edit: I intend to update this example some day soon.
    Hello,

    Am new to socket programming, and i like your example. but i want to rap this up in a class, so that i can share it among my app that needs socket functionality.

    can you help me please?
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  34. #154
    Member
    Join Date
    Jul 2010
    Posts
    63

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Hey Atheist can you explain this code a little??? I send you one message if you can just answer me i need help urgently
    Thanks

  35. #155
    New Member
    Join Date
    Apr 2010
    Posts
    2

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Hello all, I am also in net programming and this example has proven very useful. A quick question though. How can the value of the Message_Delimiter be changed? Thanks.

  36. #156
    New Member
    Join Date
    Oct 2010
    Posts
    2

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by TokersBall_CDXX View Post
    oddly enough though if I make the thread sleep for 1 ms during the read loop.... things work properly in both the IDE and the compiled exe.
    Sorry for replying to this really old posts, but the past week I've been trying to use this code myself, and had the same problem as you. It took me a couple of days to find the problem...

    In the constructor of the connectedClient class, the thread is started to start listening. However, in the doListen function, the event-handlers are added AFTER the line "Dim connClient As New ConnectedClient(incomingClient)". This means that it is possible that data comes in before the eventhandlers are added, meaning that the data is lost. I fixed the connectedClient class like this:

    Code:
        Sub New(ByVal client As System.Net.Sockets.TcpClient)
            mClient = client
        End Sub
    
        Public Sub StartReading()
            readThread = New System.Threading.Thread(AddressOf doRead)
            readThread.IsBackground = False
            readThread.Start()
        End Sub

  37. #157
    New Member
    Join Date
    Oct 2010
    Posts
    2

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Quote Originally Posted by bmaster View Post
    Code:
        Sub New(ByVal client As System.Net.Sockets.TcpClient)
            mClient = client
        End Sub
    
        Public Sub StartReading()
            readThread = New System.Threading.Thread(AddressOf doRead)
            readThread.IsBackground = False
            readThread.Start()
        End Sub
    Oh, and then of course after creating the new client, and doing the AddHandler-stuff, you call StartReading, otherwise not much data will be read

  38. #158
    New Member
    Join Date
    Jan 2007
    Location
    Croatia/Čepin
    Posts
    13

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    Hi!
    I have 1 question.

    how must look send message from client so it would be recognized by server on doread sub and send it to messagerecived sub?

    I try this on client:
    HTML Code:
    sw.Write("CONNECT|" & txtNick.Text)
    sw.Write("DISCONNECT|" & txtNick.Text)
    sw.Write("MESSAGE|" & txtNick.Text & "|" & txtMessage.Text)
    but every time can't pass on message_delimiter

    Code:
    If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then..
    This is code od doRead()

    Code:
    Private Const MESSAGE_DELIMITER As Char = ControlChars.Cr
    
     Private Sub doRead()
    
            Const BYTES_TO_READ As Integer = 255
            Dim readBuffer(BYTES_TO_READ) As Byte
            Dim bytesRead As Integer
            Dim sBuilder As New System.Text.StringBuilder
            Do
                bytesRead = mClient.GetStream.Read(readBuffer, 0, BYTES_TO_READ)
                If (bytesRead > 0) Then
                    Dim message As String = System.Text.Encoding.UTF8.GetString(readBuffer, 0, bytesRead)
                    If (message.IndexOf(MESSAGE_DELIMITER) > -1) Then
    
    
                        Dim subMessages() As String = message.Split(MESSAGE_DELIMITER)
    
                        'The first element in the subMessages string array must be the last part of the current message.
                        'So we append it to the StringBuilder and raise the dataReceived event
                        sBuilder.Append(subMessages(0))
                        RaiseEvent dataReceived(Me, sBuilder.ToString)
                        sBuilder = New System.Text.StringBuilder
    
    
                        'If there are only 2 elements in the array, we know that the second one is an incomplete message,
                        'though if there are more then two then every element inbetween the first and the last are complete messages:
                        If subMessages.Length = 2 Then
                            sBuilder.Append(subMessages(1))
                        Else
                            For i As Integer = 1 To subMessages.GetUpperBound(0) - 1
                                RaiseEvent dataReceived(Me, subMessages(i))
                            Next
                            sBuilder.Append(subMessages(subMessages.GetUpperBound(0)))
                        End If
                    Else
    
                        'MESSAGE_DELIMITER was not found in the message, so we just append everything to the stringbuilder.
                        sBuilder.Append(message)
                    End If
                End If
            Loop
        End Sub
    How can I fix my problem?
    Please help =)

  39. #159
    New Member
    Join Date
    Jan 2007
    Location
    Croatia/Čepin
    Posts
    13

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    I fix the error and now it's working perfect but now I have another problem

    when I send form server 2 message in same time client recived message in one line like this:
    NEW|BlackOneUSERLIST|nickname1USERLIST|nickname2

    but i need to recived message look like this
    1. message NEW|BlackOne
    2. message USERLIST|nickname1
    3. message USERLIST|nickname2



    Case "CONNECT"
    If GetClientByName(data(1)) Is Nothing Then
    sender.Username = data(1)
    sender.SendMessage("WELCOME|" & txtServerName.Text & "|" & txtMessageOfDay.Text & ControlChars.Cr)
    Setmessage("New user connected to server: " & data(1))
    adduser(data(1))
    Dim i As Integer

    For Each cc As ConnectedClient In clients
    cc.SendMessage("NEW|" & sender.Username & ControlChars.Cr)
    Next

    For i = 0 To lbUserlist.Items.Count - 1
    sender.SendMessage("USERLIST|" & lbUserlist.Items(i) & ControlChars.Cr)
    Next

    Else

    End If



    how can I fix that error?

    Sorry for bed English

  40. #160
    New Member
    Join Date
    Nov 2008
    Posts
    1

    Re: [RESOLVED] [2008] Can I add a TCPClient Component

    hey guys, i'm trying to make a client send messages to another client, but i fail every time,and when i do manage, my privatemessage form freezez, or client2 can't send back messages to client1, pls help

Page 4 of 5 FirstFirst 12345 LastLast

Posting Permissions

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



Click Here to Expand Forum to Full Width