top of page

(5) Peer To Peer Chat Tutorial in Go

  • Writer: Jason Fantl
    Jason Fantl
  • Nov 1, 2022
  • 2 min read

Concept

The first thing we should do is create an identity for each user, that way people know who the messages are coming from (this is separate from NodeID, but had we not hidden NodeID under abstraction, we could have used it instead). Once we have usernames, we will want to be able to directly talk to someone. All this will take is sending messages along with who they are intended for, and trust no one else reads them if its not their name, kind of like physical mail.


Then that's it, we have a dynamic peer to peer network! People joining and leaving, messages being propagated through the entire network, and even a small chat application on top of the network.


ree

Unlike the animation above, our network is designed so that it shouldn't separate itself. A more realistic animation would have nodes connecting to each other at random, regardless of geometric distance, but that would make the visualization less intuitive.


Code

All the printing done by the network code will be put into a log file instead (easy as replacing fmt.Print with log.Print), that leaves the terminal just for messaging.


We will use a struct to send our messages along with the sender, but the network only accepts byte arrays. This means using an encoder to turn our struct into a byte array and back, which JSON is great at (not gob, since gob requires sending an initial framing packet to establish a connection between an encoding/decoding pair, which doesn't match our multi-connected network).


floodnet/network.go


floodnet/joining.go


main.go


We have a few commands now. 'exit' or 'quit' will close the program, 'set username' will prompt you to change your username, and '@friends_username a personal message' will send a personal message to the person with username 'friends_username'.


In a few terminals run the code we've written so far. Then set some usernames and try sending both undirected and direct messages.

go build -o chat && ./chat


Next

The project is essentially finished here. Now you can see how easily we can build on top of this flood-fill network. Of course, different applications can be built on top of this: a blockchain, sensor network, or anything else that requires a dynamic network which doesn't use pre-existing architecture. The next post will be a list of security related modifications, they will be a bit complicated, and not necessary, so feel free to stop here. You now have a peer to peer network!

 
 
 

Comments


  • 3178158
  • 25231
  • LinkedIn

©2021 by Simply Confusing

bottom of page