School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become an Expert!

Join 306,996 Programmers for FREE! Get instant access to thousands of experts, tutorials, code snippets, and more! There are 1,969 people online right now. Registration is fast and FREE... Join Now!




P2P Connections

2 Pages V  1 2 >  
Reply to this topicStart new topic

> P2P Connections, VB.NET

Rating  5
the_hangman
Group Icon



post 28 Nov, 2006 - 02:06 PM
Post #1


NOTE: This tutorial is for VB.NET

This tutorial will show how to create a P2P (Peer To Peer) connection with another user, and transfer data in the form of strings. This is only a basic tutorial, but the logic can be extended to anything. I've already used this to create an Instant Messager, a few multi player online games, and some other basic information exchange programs.

First things first, let's start a form to work with. Obviously you don't need all or any of these items on your form, and you may even want to add more (such as a field to enter an IP address). Create a form and add 1 Button, 1 TextBox, and 1 Timer. Make the textbox big enough to type in. For the timer set the interval property in the properties box to 1 and the enabled property to True. It should look something like this:
Attached Image

Now let's take a look at those codes. Bring up the Code window for Form 1. We are going to need to import a few namespaces in the area before Public Class Form1.

CODE
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO

Public Class Form1


The System.Net.Sockets namespace will allow us to make and listen to connections from and with other users.
The System.Threading namespace will allow us to do several things at the same time without interfering with one another
The System.IO namespace will allow us to send and receive information over our connection

Next we will need a few variables

CODE
Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = ""


The variable Listener is a TcpListener that listens for incoming connections (data someone is sending you) at a specific port. A port is just the gateway that you want information to flow through. It doesn't really matter what port you use, as long as it's not already being used. There are 65,535 ports to choose from. The lower numbers are used more often and the higher are usually open, so you will be more likely to find an open port if you pick a high number. We are going to use the last port, for the sake of it.

The variable Client is a TcpClient, which is basically the other computer that you are sending information.

The variable Message is just a String to hold incoming messages. We are going to make it empty when the form first starts, because there is no message yet.


When Form1 first loads we want to start a separate thread to take care of some repetitive tasks that would otherwise freeze your application.

CODE
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ListThread As New Thread(New ThreadStart(AddressOf Listening)) 'Creates the thread
        ListThread.Start() 'Starts the thread
    End Sub


This part should be pretty easy to understand. Dim ListThread creates the thread. AddressOf is the Address (sub) that you want the thread to start working on. And ListThread.Start() starts the thread.

Obviously the sub Listening doesn't exist yet, so we need to create it. The only thing this sub needs to do is start our TcpListener (remember it was called Listener?)

CODE
    Private Sub Listening()
        Listener.Start()
    End Sub


The reason we added this to the thread is because if we didn't it would eventually freeze up your application.
Now we need to do something when the TcpListener hears a connection.
NOTE: At this part I use the timer. I have yet been unsuccessful in creating a loop that will listen for a connection without causing problems somewhere. If you know of a way, it will work here just fine I'm sure, and maybe you could even help me out?

CODE
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Listener.Pending = True Then
            Message = ""
            Client = Listener.AcceptTcpClient()

            Dim Reader As New StreamReader(Client.GetStream())
            While Reader.Peek > -1
                Message = Message + Convert.ToChar(Reader.Read()).ToString
            End While

            MsgBox(Message, MsgBoxStyle.OkOnly)
        End If


What this does is checks 1000 times a second (if the timer interval is set to 1) to see if the TcpListener heard a connection. If it does, then it proceeds to collect the message.

First we have to make sure variable Message is empty. No message has come in yet remember? Then we need to accept the connection (sort of like answering the phone). We'll use the TcpClient variable that we created earlier (Client) to hold the client (other computer).

Next we need to start a stream for the data to come in. So we create a StreamReader that can read the stream. The argument for the StreamReader is what stream to read. We initiate the stream from the client with Client.GetStream() as the argument.

Now it's time to read from the stream. Since we can't read a messages that isn't there, we need to make sure that there is something to read. To do this we will read one character at a time, but we will use Reader.Peek() to peek ahead one space and make sure there is a letter there, which will return the index of the next letter. If there is no letter it will return -1, therefore, as long as Reader.Peek() comes back greater than -1 we can keep going.
Next we want to save the message we are receiving in our String variable Message. Since we are only getting one letter at a time we want to add each letter onto the end of what is already there. So we use Message = Message + the next letter. And finally we read the next letter with Reader.Read() This letter is going to come in as machine data that is pretty much gibberish to people, so we will have to convert it to readable characters first.
Also, we want to see the message so we are just going to display it in a message box.

The last thing we need to do to complete our P2P connection, is send a message to someone, which we will do when we click on Button1

CODE
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Client = New TcpClient("127.0.0.1", 65535)

        Dim Writer As New StreamWriter(Client.GetStream())
        Writer.Write(TextBox1.Text)
        Writer.Flush()
    End Sub


Once again we are going to use the variable Client to establish a connection with the other computer. But this time we need to determine who we are sending the data to, and what port we are using. Since this is a demo we are just going to connect to ourselves (and yes, talk to ourselves), by using the IP 127.0.0.1 (the universal home address in case you didn't know). You may want to add a TextBox to type in a different address and use that as the IP to connect to (something along the lines of TextBox2.Text). Then we want use the same port to make sure the info gets where it's going.

Now let's create a stream to write our data on. Create a StreamWrite that can write to streams. Like the StreamReader, it has an argument of which stream to write to, and we will use Client.GetStream() again. After that we write the text from TextBox1 into the stream. And when it's all done we flush it, which is, for all intensive purposes, like flushing a toilet to make everything go down the pipe where it needs to go.

Oh and make sure you close the code with:
CODE

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Listener.Stop()
    End Sub
End Class


You should be able to run the application now, and send yourself messages. I've included a textfile with the typed code for you to look at if you need help. Have fun!


For the record:
- StreamWriter and StreamReader are part of the System.IO namespace
- TcpClient and TcpListener are part of the System.Net.Socket namespace
- Thread is part of the System.Threading namespace

This post has been edited by the_hangman: 29 Nov, 2006 - 05:06 AM


Attached File(s)
Attached File  P2P_Connection_Code.txt ( 1.46k ) Number of downloads: 2238
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

brottmayer
**



post 8 Apr, 2007 - 07:00 PM
Post #2
QUOTE(the_hangman @ 28 Nov, 2006 - 03:06 PM) *



Quick question? When selecting a different IP address, this would be the other PC's IP that I would input into TextBox2.Text and it will go into here like so:

CODE

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Client = New TcpClient(TextBox2.Text, 60798)
        Dim Writer As New StreamWriter(Client.GetStream())
        Writer.Write(TextBox1.Text)
        Writer.Flush()
    End Sub

Like so?

And another question? How can I set this up to have the messages sent and received show up in textbox1.text, just like the ones of msn and yahoo? Thanks. and By the way, AWESOME tutorial!! Learned a lot!

brottmayer

Go to the top of the page
+Quote Post

Codezilla
*



post 14 Jun, 2007 - 12:25 PM
Post #3
This tutorial is by far the best I've seen for an introductory explanation on the use of TCPListener/Client. I've been looking for something like this for 2 days now, and thanks to you I now have the basic rudimentary knowledge I need to really start getting knees-deep into this without getting an aneurism. Thank you.
Go to the top of the page
+Quote Post

dmonroe
*



post 7 Nov, 2007 - 11:05 AM
Post #4
This tutorial was marvelous. Thank you.
One quick question, any idea how to do a broadcast with this? I have tried using 255.255.255.255, but it returns an unhandled socket exception error.

This has really helped with a project I am working on.[size=1]
Go to the top of the page
+Quote Post

HAX
*



post 12 Nov, 2007 - 12:17 PM
Post #5
Can somebody help me plz
i folow the tutorial to the letter and i get an error message saying target machine activly refused

plz help
Go to the top of the page
+Quote Post

Rozie0910
*



post 15 Oct, 2008 - 05:33 PM
Post #6
i already try this code..
i dont get an error and no output came out...
could u help me..
Go to the top of the page
+Quote Post

eLampe
*



post 20 Feb, 2009 - 04:10 PM
Post #7
Ok, if I get this to work I will be thrilled, but every time I run it I get this:
IPB Image
Go to the top of the page
+Quote Post

Asscotte
Group Icon



post 23 Feb, 2009 - 08:32 AM
Post #8
Just a note u might want to add as an after thought - I added so e trys and catches not for any other purpose other than then u can have the timer running all the time wich helps quite a bit. ph34r.gif
Go to the top of the page
+Quote Post

hacksys
Group Icon



post 23 Feb, 2009 - 09:38 AM
Post #9
How could i expand this to allow multiple users in a chat room / irc setting. Also how could i use / get the ip of anyone connected to the chat room?

Thanks in advance
Go to the top of the page
+Quote Post

Asscotte
Group Icon



post 26 Feb, 2009 - 10:46 AM
Post #10
How I did this was to cheat a little Im using winsock to find my own ip u can use your own method but what it does is loads it into a lebel on form load so when they send something ...
CODE

This Bit-

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Client = New TcpClient("127.0.0.1", 65535)

        Dim Writer As New StreamWriter(Client.GetStream())
        Writer.Write(TextBox1.Text)
        Writer.Flush()
    End Sub


I change the  Client = New TcpClient("127.0.0.1", 65535) to
Client = New TcpClient((textbox3.text), 65535)

and Writer.Write(TextBox1.Text)
to Writer.Write((TextBox1.Text)+ vbcrlf + "sent from - " + (label1.text))

that means that you get your message ie hello then theres one line down then it shows the senders ip that was
sent with that message Baisicly that could be extended for anything like time date other random introducing text
and I even used it to introduce a Nickname (code is following)

Writer.Write((textbox4.text) + " sent you a prezzie(or some other text) at - "+(my.system.clock.localtime) + vbcrlf  +(TextBox1.Text))


I hope that, that helps also If you want a chat message when someone connects to you then you just need to
add some script like the above for this section...

CODE

    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Listener.Pending = True Then
            textbox2.text = (textbox2.text + "Message Pending" + vbcrlf)
            Message = ""
            Client = Listener.AcceptTcpClient()

            Dim Reader As New StreamReader(Client.GetStream())
            While Reader.Peek > -1
                Message = Message + Convert.ToChar(Reader.Read()).ToString
            End While

            textbox2.text = (textbox2.text +Message + vbcrlf)
        End If


The above code will need some work to get the desired effect but it should give you the right idea, you should be able to work out which textboxes are wich but if not then -

- textbox1 = message to be sent
- textbox2 = recieved message
- textbox3 = Ip addy
- textbox4 = nickname
- label1 = winsock labeled label with my/your IP in it


Whooooooooo Great tutorial!!!!!
Go to the top of the page
+Quote Post

silvanbusuttil
*



post 6 Apr, 2009 - 04:07 AM
Post #11
what shall i do exactly with

Reader.Peek()

it says "Reader is not declared"
because i'm getting errors with vb express edition 2008

This post has been edited by silvanbusuttil: 6 Apr, 2009 - 04:54 AM
Go to the top of the page
+Quote Post

silvanbusuttil
*



post 6 Apr, 2009 - 05:29 AM
Post #12
hi i fixed the errors that i had but now i'm trying to run it but i'm not getting any output.... or response. here is my code.

CODE


Imports System.Net.Sockets
Imports System.Threading
Imports System.IO
Public Class Form1
    Dim Listener As New TcpListener(28960)
    Dim Client As New TcpClient
    Dim Message As String = ""
    Private Sub btn_Send_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Send.Click
        Client = New TcpClient((txt_ip.Text), 28960)
        Dim Writer As New StreamWriter(Client.GetStream())
        Writer.Write((txtbx_conversation.Text) + vbCrLf)
        Writer.Flush()
    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ListThread As New Thread(New ThreadStart(AddressOf Listening)) 'Creates the thread
        ListThread.Start() 'Starts the thread
    End Sub
    Private Sub Listening()
        Listener.Start()
    End Sub
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Listener.Pending = True Then
            txtbx_conversation.Text = (txtbx_conversation.Text + "Message Pending" + vbCrLf)
            Message = ""
            Client = Listener.AcceptTcpClient()

            Dim Reader As New StreamReader(Client.GetStream())
            While Reader.Peek > -1
                Message = Message + Convert.ToChar(Reader.Read()).ToString
            End While

            txtbx_conversation.Text = (txtbx_conversation.Text + Message + vbCrLf)
        End If
    End Sub

End Class



i tried to change the tcp port to 28960 but still no output.. Please note that i don't have any firewalls... so the port is unblocked. Thanks

This post has been edited by silvanbusuttil: 6 Apr, 2009 - 05:30 AM
Go to the top of the page
+Quote Post

djwkd
*



post 13 Apr, 2009 - 02:55 PM
Post #13
QUOTE(silvanbusuttil @ 6 Apr, 2009 - 04:07 AM) *

what shall i do exactly with

Reader.Peek()

it says "Reader is not declared"
because i'm getting errors with vb express edition 2008


Check that you included this line of code-------
CODE
Dim Reader As New StreamReader(Client.GetStream())

Go to the top of the page
+Quote Post

Orpheus
*



post 7 May, 2009 - 05:12 AM
Post #14
Thanks a BILLION for this AWESOME tutorial biggrin.gif just was I was looking for, Been planning on making some P2P programs with a mate for some wokr projects, thanks alot biggrin.gif
Go to the top of the page
+Quote Post

Orpheus
*



post 13 May, 2009 - 03:53 AM
Post #15
Sorry for the double post!

after, nearly a week of working on this code, I've made a Basic Instant messengering system, with file sending capabilities, but, I'm having trouble sending it outside of a LOCAL network.
Simply put, I don't understand how to connect two PC's via my program via the internet.
Do I need to specify a particular IP? do both computers have to connect to one another's IPs? or to a central hub?
very confused about it, and I don't know any scripters at my school, and I'm really interested in learning how to do this

*note* I learn best from sample code with notes or annotations, I learnt VB scripting in a few weeks using this method.
Go to the top of the page
+Quote Post

noorahmad
Group Icon



post 13 May, 2009 - 03:58 AM
Post #16
nice tutorial
Go to the top of the page
+Quote Post

thatsmeprashant
*



post 26 Jun, 2009 - 04:40 AM
Post #17
hi....what am i supposed to do to send image file to the other computer....any help ....
Go to the top of the page
+Quote Post

Orpheus
*



post 26 Jun, 2009 - 04:43 AM
Post #18
QUOTE(thatsmeprashant @ 26 Jun, 2009 - 04:40 AM) *

hi....what am i supposed to do to send image file to the other computer....any help ....


You could try the C4F P2P samples smile.gif

C4F of course means coding for fun smile.gif
you can download it and many others from here

Regards Orpheus
Go to the top of the page
+Quote Post

gadile2
*



post 1 Jul, 2009 - 04:29 AM
Post #19
QUOTE(Rozie0910 @ 15 Oct, 2008 - 05:33 PM) *

i already try this code..
i dont get an error and no output came out...
could u help me..


Hey,
I had the same problem.
I figured out that the reason was that the timer was disabled.

Just choose the timer, go to its properties and change "Enable" to true.

That's it!!!!!!

QUOTE(the_hangman @ 28 Nov, 2006 - 02:06 PM) *

NOTE: This tutorial is for VB.NET

This tutorial will show how to create a P2P (Peer To Peer) connection with another user, and transfer data in the form of strings. This is only a basic tutorial, but the logic can be extended to anything. I've already used this to create an Instant Messager, a few multi player online games, and some other basic information exchange programs.

First things first, let's start a form to work with. Obviously you don't need all or any of these items on your form, and you may even want to add more (such as a field to enter an IP address). Create a form and add 1 Button, 1 TextBox, and 1 Timer. Make the textbox big enough to type in. For the timer set the interval property in the properties box to 1 and the enabled property to True. It should look something like this:
Attached Image

Now let's take a look at those codes. Bring up the Code window for Form 1. We are going to need to import a few namespaces in the area before Public Class Form1.

CODE
Imports System.Net.Sockets
Imports System.Threading
Imports System.IO

Public Class Form1


The System.Net.Sockets namespace will allow us to make and listen to connections from and with other users.
The System.Threading namespace will allow us to do several things at the same time without interfering with one another
The System.IO namespace will allow us to send and receive information over our connection

Next we will need a few variables

CODE
Dim Listener As New TcpListener(65535)
Dim Client As New TcpClient
Dim Message As String = ""


The variable Listener is a TcpListener that listens for incoming connections (data someone is sending you) at a specific port. A port is just the gateway that you want information to flow through. It doesn't really matter what port you use, as long as it's not already being used. There are 65,535 ports to choose from. The lower numbers are used more often and the higher are usually open, so you will be more likely to find an open port if you pick a high number. We are going to use the last port, for the sake of it.

The variable Client is a TcpClient, which is basically the other computer that you are sending information.

The variable Message is just a String to hold incoming messages. We are going to make it empty when the form first starts, because there is no message yet.


When Form1 first loads we want to start a separate thread to take care of some repetitive tasks that would otherwise freeze your application.

CODE
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim ListThread As New Thread(New ThreadStart(AddressOf Listening)) 'Creates the thread
        ListThread.Start() 'Starts the thread
    End Sub


This part should be pretty easy to understand. Dim ListThread creates the thread. AddressOf is the Address (sub) that you want the thread to start working on. And ListThread.Start() starts the thread.

Obviously the sub Listening doesn't exist yet, so we need to create it. The only thing this sub needs to do is start our TcpListener (remember it was called Listener?)

CODE
    Private Sub Listening()
        Listener.Start()
    End Sub


The reason we added this to the thread is because if we didn't it would eventually freeze up your application.
Now we need to do something when the TcpListener hears a connection.
NOTE: At this part I use the timer. I have yet been unsuccessful in creating a loop that will listen for a connection without causing problems somewhere. If you know of a way, it will work here just fine I'm sure, and maybe you could even help me out?

CODE
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If Listener.Pending = True Then
            Message = ""
            Client = Listener.AcceptTcpClient()

            Dim Reader As New StreamReader(Client.GetStream())
            While Reader.Peek > -1
                Message = Message + Convert.ToChar(Reader.Read()).ToString
            End While

            MsgBox(Message, MsgBoxStyle.OkOnly)
        End If


What this does is checks 1000 times a second (if the timer interval is set to 1) to see if the TcpListener heard a connection. If it does, then it proceeds to collect the message.

First we have to make sure variable Message is empty. No message has come in yet remember? Then we need to accept the connection (sort of like answering the phone). We'll use the TcpClient variable that we created earlier (Client) to hold the client (other computer).

Next we need to start a stream for the data to come in. So we create a StreamReader that can read the stream. The argument for the StreamReader is what stream to read. We initiate the stream from the client with Client.GetStream() as the argument.

Now it's time to read from the stream. Since we can't read a messages that isn't there, we need to make sure that there is something to read. To do this we will read one character at a time, but we will use Reader.Peek() to peek ahead one space and make sure there is a letter there, which will return the index of the next letter. If there is no letter it will return -1, therefore, as long as Reader.Peek() comes back greater than -1 we can keep going.
Next we want to save the message we are receiving in our String variable Message. Since we are only getting one letter at a time we want to add each letter onto the end of what is already there. So we use Message = Message + the next letter. And finally we read the next letter with Reader.Read() This letter is going to come in as machine data that is pretty much gibberish to people, so we will have to convert it to readable characters first.
Also, we want to see the message so we are just going to display it in a message box.

The last thing we need to do to complete our P2P connection, is send a message to someone, which we will do when we click on Button1

CODE
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Client = New TcpClient("127.0.0.1", 65535)

        Dim Writer As New StreamWriter(Client.GetStream())
        Writer.Write(TextBox1.Text)
        Writer.Flush()
    End Sub


Once again we are going to use the variable Client to establish a connection with the other computer. But this time we need to determine who we are sending the data to, and what port we are using. Since this is a demo we are just going to connect to ourselves (and yes, talk to ourselves), by using the IP 127.0.0.1 (the universal home address in case you didn't know). You may want to add a TextBox to type in a different address and use that as the IP to connect to (something along the lines of TextBox2.Text). Then we want use the same port to make sure the info gets where it's going.

Now let's create a stream to write our data on. Create a StreamWrite that can write to streams. Like the StreamReader, it has an argument of which stream to write to, and we will use Client.GetStream() again. After that we write the text from TextBox1 into the stream. And when it's all done we flush it, which is, for all intensive purposes, like flushing a toilet to make everything go down the pipe where it needs to go.

Oh and make sure you close the code with:
CODE

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Listener.Stop()
    End Sub
End Class


You should be able to run the application now, and send yourself messages. I've included a textfile with the typed code for you to look at if you need help. Have fun!


For the record:
- StreamWriter and StreamReader are part of the System.IO namespace
- TcpClient and TcpListener are part of the System.Net.Socket namespace
- Thread is part of the System.Threading namespace


unbelievable!!!

I just spent a week and a half to build some kind of client/server application but nothing worked; I tried so many examples and tips but still nothing worked.
Finally I found this code and finally manage to operate it.
Thank you so much!! An Oskar for the best post!
Go to the top of the page
+Quote Post

The Unknown
*



post 4 Aug, 2009 - 12:51 AM
Post #20
How can you change to port the "Listener" is listening to without all the errors? eg being able to have a txt box and being able to change the port it sends/receives from when the text in the textbox is changed
Go to the top of the page
+Quote Post


2 Pages V  1 2 >
Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 06:02AM

Live Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Tutorials

Programming

Web Development

Reference Sheets

Code Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month