Below is a go code, which tcp server, client and mqtt client implemented
Flow: (1) it receives tcp requests (2) Accepts and modifies the header (3) published to its respective topic on the mqtt broker (4) On a successful publish, it sends the packet to another tcp server
func main() {
mqttListener, err := net.Listen("tcp", ":8181")
if err != nil {
log.Fatalf("Failed to start MQTT server: %v", err)
}
client, ctx := brokerConnect()
println("Connected to the broker!!")
fmt.Println("MQTT server listening on port 8181...")
go func() {
for {
**1** println("starting to accept connection from the socket")
conn, err := mqttListener.Accept()
if err != nil {
log.Printf("Failed to accept MQTT connection: %v", err)
continue
}
**2** println("reading from the socket")
conn.SetDeadline(time.Time{})
**3** println("rDeadline is set")
go handleMQTT(conn)
}
}()
defer httpListener.Close()
defer mqttListener.Close()
go func() {
for {
p, id := createPubMsg()
pub, errp := client.Publish(ctx, p)
httpResponseWriter(pub, errp, id)
}
}()
go func() {
for {
tcpClient()
}
}()
println("Main thread")
// Keep the program running
select {}
}
func createPubMsg() (*mqtt.Publish, string) {
println("Entered the createPubMsg() function")
**publishInfo := <-chnMQTT**
...
...
println("packet created succesfully!!!")
return p, publishInfo.id
}
func httpResponseWriter(pub *mqtt.PublishResponse, errp error, id string) {
......
......
// http.response to []bytes
responseBytes, err := httputil.DumpResponse(resp, true /* include body */)
**chnTCP <- responseBytes**
}
func tcpClient() {
println("inside tcpClient() function")
**payload := <-chnTCP**
//creating a tcp connection and sending payload over it
.....
}
func handleMQTT(conn net.Conn) {
defer conn.Close()
println("Inside the tcp server handler")
buf := &bytes.Buffer{}
//<!> remember to make it concurrent
reader := bufio.NewReader(conn)
/// extract fields from the payload
....
**chnMQTT <- //sending the data**
}
Scenario: When I am sending 1 request, it is being processed and expected response is coming, but when I am sending 2, I can see the requests being reached at the server but there are no print statements being executed for the second request.
Also, the client that is connected to this server sends both of the requests on the same connection.
What could be the possible issue with the above code.
poweroff is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.