• (3 Pages)
  • +
  • 1
  • 2
  • 3

P2P Connections VB.NET Rate Topic: ***** 5 Votes

#1 the_hangman  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 14
  • View blog
  • Posts: 602
  • Joined: 18-January 06

Posted 28 November 2006 - 03: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.

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

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.

	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?)

	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?

	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

	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:
	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

Attached File(s)


This post has been edited by the_hangman: 29 November 2006 - 06:06 AM


Is This A Good Question/Topic? 2
  • +

Replies To: P2P Connections

#2 brottmayer  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 67
  • Joined: 21-January 07

Posted 08 April 2007 - 08:00 PM

View Postthe_hangman, on 28 Nov, 2006 - 03:06 PM, said:



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:

	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
Was This Post Helpful? 0
  • +
  • -

#3 Codezilla  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 14-June 07

Posted 14 June 2007 - 01:25 PM

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.
Was This Post Helpful? 0
  • +
  • -

#4 dmonroe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-November 07

Posted 07 November 2007 - 12:05 PM

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]
Was This Post Helpful? 0
  • +
  • -

#5 HAX  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 9
  • Joined: 13-April 07

Posted 12 November 2007 - 01:17 PM

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
Was This Post Helpful? 0
  • +
  • -

#6 Rozie0910  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 13-October 08

Posted 15 October 2008 - 06:33 PM

i already try this code..
i dont get an error and no output came out...
could u help me..
Was This Post Helpful? 0
  • +
  • -

#7 eLampe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 22-October 08

Posted 20 February 2009 - 05:10 PM

Ok, if I get this to work I will be thrilled, but every time I run it I get this:
Posted Image
Was This Post Helpful? 0
  • +
  • -

#8 Asscotte  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 35
  • View blog
  • Posts: 610
  • Joined: 08-February 09

Posted 23 February 2009 - 09:32 AM

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:
Was This Post Helpful? 0
  • +
  • -

#9 hacksys  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 27-December 08

Posted 23 February 2009 - 10:38 AM

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
Was This Post Helpful? 0
  • +
  • -

#10 Asscotte  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 35
  • View blog
  • Posts: 610
  • Joined: 08-February 09

Posted 26 February 2009 - 11:46 AM

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 ...
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...

	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!!!!!
Was This Post Helpful? 0
  • +
  • -

#11 silvanbusuttil  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-April 09

Posted 06 April 2009 - 05: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

This post has been edited by silvanbusuttil: 06 April 2009 - 05:54 AM

Was This Post Helpful? 0
  • +
  • -

#12 silvanbusuttil  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 06-April 09

Posted 06 April 2009 - 06:29 AM

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.


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: 06 April 2009 - 06:30 AM

Was This Post Helpful? 0
  • +
  • -

#13 djwkd  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 06-March 09

Posted 13 April 2009 - 03:55 PM

View Postsilvanbusuttil, on 6 Apr, 2009 - 04:07 AM, said:

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-------
 Dim Reader As New StreamReader(Client.GetStream()) 

Was This Post Helpful? 0
  • +
  • -

#14 Orpheus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 26-April 09

Posted 07 May 2009 - 06:12 AM

Thanks a BILLION for this AWESOME tutorial :D just was I was looking for, Been planning on making some P2P programs with a mate for some wokr projects, thanks alot :D
Was This Post Helpful? 0
  • +
  • -

#15 Orpheus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 26-April 09

Posted 13 May 2009 - 04:53 AM

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.
Was This Post Helpful? 0
  • +
  • -

  • (3 Pages)
  • +
  • 1
  • 2
  • 3