A constructor function that generates and returns a new PubSub for a given P2PHost, username and roomname
(p2phost *p2p.P2P, clientName string, topicName string)
| 120 | // A constructor function that generates and returns a new |
| 121 | // PubSub for a given P2PHost, username and roomname |
| 122 | func JoinPubSub(p2phost *p2p.P2P, clientName string, topicName string) (*PubSub, error) { |
| 123 | |
| 124 | // Create a PubSub topic with the room name |
| 125 | topic, err := p2phost.PubSub.Join(fmt.Sprintf("pub-sub-p2p-%s", topicName)) |
| 126 | // Check the error |
| 127 | if err != nil { |
| 128 | return nil, err |
| 129 | } |
| 130 | |
| 131 | // Subscribe to the PubSub topic |
| 132 | sub, err := topic.Subscribe() |
| 133 | // Check the error |
| 134 | if err != nil { |
| 135 | return nil, err |
| 136 | } |
| 137 | |
| 138 | // Check the provided clientname |
| 139 | if clientName == "" { |
| 140 | // Use the default client name |
| 141 | clientName = defaultclient |
| 142 | } |
| 143 | |
| 144 | // Check the provided topicname |
| 145 | if topicName == "" { |
| 146 | // Use the default topic name |
| 147 | topicName = defaulttopic |
| 148 | } |
| 149 | |
| 150 | // Create cancellable context |
| 151 | pubsubctx, cancel := context.WithCancel(context.Background()) |
| 152 | |
| 153 | // Create a PubSub object |
| 154 | PubSub := &PubSub{ |
| 155 | Host: p2phost, |
| 156 | |
| 157 | Inbound: make(chan chatmessage), |
| 158 | Outbound: make(chan string), |
| 159 | Logs: make(chan chatlog), |
| 160 | |
| 161 | psctx: pubsubctx, |
| 162 | pscancel: cancel, |
| 163 | pstopic: topic, |
| 164 | psub: sub, |
| 165 | |
| 166 | ClientName: clientName, |
| 167 | TopicName: topicName, |
| 168 | selfid: p2phost.Host.ID(), |
| 169 | } |
| 170 | |
| 171 | //// Start the subscribe loop |
| 172 | //go PubSub.SubLoop() |
| 173 | //// Start the publish loop |
| 174 | //go PubSub.PubLoop() |
| 175 | |
| 176 | pss.join[topicName] = PubSub |
| 177 | go PubSub.PubLoop() |
| 178 | go PubSub.SubLoop() |
| 179 | go PubSub.Writer() |