How to fill a map with requests from client

87 views
Skip to first unread message

snk

unread,
Jan 3, 2020, 2:14:22 AM1/3/20
to golang-nuts
I am a beginner in Golang, This is a TCP server that receives requests and sends back a hello message to the client attached with the client's message(name)
 how can I fill those requests into a map without erasing the previous request?
 this is the code, the request is appended to the map but when the next comes, it replaces the current on.


 // Goroutine and Socket programming TCP server
//**************************************************
//                 TCP
//----------------------------------------------------------

package main

import (
   
"bufio"
   
"fmt"
   
"net"
   
"time"
)
// check if there is any error and send a message. but it's better to remove panic later (it's not recommended to use it)
//***********************************************************************************************************************
func check
(err error, message string) {
   
if err != nil {
        panic
(err)
   
}
    fmt
.Printf("%s\n", message)
}
// Create the client structure that contains the client's name and the connection
//****************************************************************************

type
ClientJob struct {
    name
string
    conn net
.Conn

}

// Create the function,the channel with type struct
//*********************************************************

func generateResponses
(clientJobs chan ClientJob) {
   
for {
       
// Wait for the next job to come off the queue.
        clientJob
:= <-clientJobs

       
// Do something thats keeps the CPU buys for a whole second.
       
for start := time.Now(); time.Now().Sub(start) < time.Second; {
       
}

       
// Send back the response.

        clientJob
.conn.Write([]byte("Hello, " + clientJob.name))

       
//clientJob:=make(chan ClientJob)
       
//name:=make(chan string)
       
//name:=<-clientJobs

        all
:= make(map[string]string) // create the map
        all
["client request"] =  clientJob.name// append the client requests on map
        fmt
.Println("All requests in the slice", all) // show all the requests in the map



   
}

}

// The main function
//***********************************

func main
() {
    clientJobs
:= make(chan ClientJob) // declare the channel used in the function above
    go generateResponses
(clientJobs)  // put the function in a goroutine

    ln
, err := net.Listen("tcp", ":8080") // connect to the port 8080, it can be changed to any port if needed
    check
(err, "Server is ready.") // show the message that the server is ready to receive
   
//fmt.Println(<-clientJobs)
   
// start checking the connection et receiving from the client and pass it into a goroutine and send it via a channel ClientJobs<-ClientJob{name, conn}
   
for {
        conn
, err := ln.Accept()
        check
(err, "Accepted connection.")

        go func
() {
            buf
:= bufio.NewReader(conn)

           
for {
                name
, err := buf.ReadString('\n')

               
if err != nil {
                    fmt
.Printf("Client disconnected.\n")
                   
break
               
}

                clientJobs
<- ClientJob{name, conn} // pass the name and conn to the clientJobs channel

           
}


       
}()
   
}
}


Amnon Baron Cohen

unread,
Jan 3, 2020, 3:51:22 AM1/3/20
to golang-nuts
        all := make(map[string]string) // create the map 
        all
["client request"] =  clientJob.name// append the client requests on map

gets called each time a request arrives.
So a new empty map gets created each time a request arrives.

The comment on the second line is wrong. The code does not "append" to the map. It overwrites the "client request" element.

MUNGAI

unread,
Jan 3, 2020, 4:02:26 AM1/3/20
to golang-nuts
Hi, as indicated above, all is a local variable to you function. Maybe you meant to have all variable on a global scope and as a map of maps.

Regards

Amnon Baron Cohen

unread,
Jan 3, 2020, 4:13:31 AM1/3/20
to golang-nuts
I have copied the problematic lines of your code into a tiny programme on the Go playground.
https://play.golang.org/p/9vMrdtC-2zX

If you run it you will see the problem.

I would play around with the code to get a feel for what is happening.

If you want to append job names, then you probably want to use a slice rather than a map.

And to get the lifetime of this slice right, it should be created outside the loop which processes each new request.

Like I said, play around with the small example, until you understand what is happening and you can get the code to do the right thing.
Then you can update your original program.

Good luck!
Message has been deleted

Prabhu Chawandi

unread,
Jan 3, 2020, 12:50:20 PM1/3/20
to snk, golang-nuts
all["client request"] =  clientJob.name// append the client requests on map
Maps are Key: Value pair, in your case as the same key ie.  "client request"  is being used, the latest value is overwriting the previous value. Add a unique key for each request to store them in same map. 

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2457abfa-04c9-476c-a2e4-b86e8e49e012%40googlegroups.com.


--
Cheers
p.
Reply all
Reply to author
Forward
0 new messages