Client/Server Code : Implementing multiple client handling

966 views
Skip to first unread message

Abhinav Srivastava

unread,
Nov 1, 2013, 10:21:18 PM11/1/13
to golan...@googlegroups.com
Hi,

I am new to golang and wanted to learn to create client server in Golang. So, I referred to one blog and found the simple client server to understand. Here is the code from the github of ER Technology Ltd with certain modifications:

Server :


package main

import (
"fmt";
"net";
"os";
)

func main() {
var (
host = "127.0.0.1";
port = "9001";
remote = host + ":" + port;
data = make([]byte, 1024);
)
fmt.Println("Initiating server... (Ctrl-C to stop)");

lis, error := net.Listen("tcp", remote);
defer lis.Close();
if error != nil {
fmt.Printf("Error creating listener: %s\n", error );
os.Exit(1);
}
for {
var response string;
var read = true;
con, error := lis.Accept();
if error != nil { fmt.Printf("Error: Accepting data: %s\n", error); os.Exit(2); }
fmt.Printf("=== New Connection received from: %s \n", con.RemoteAddr());
for read {
n, error := con.Read(data);
if error== nil{
//fmt.Println(string(data[0:n])); // Debug
response = response + string(data[0:n]);
}else{
fmt.Printf("Reading data : done\n", );
read = false;
}
}
fmt.Println("Data send by client: " + response);
con.Close();
}
}


Client :

package main

import (
"fmt";
"net";
"os";
)

func main() {
var (
host = "127.0.0.1";
port = "9001";
remote = host + ":" + port;
   msg string=""
)
var inp string
con, error := net.Dial("tcp",remote);
defer con.Close();
if error != nil { fmt.Printf("Host not found: %s\n", error ); os.Exit(1); }

for inp!="quit" {
   fmt.Scanf("%s",&inp);
   msg+=inp;
}
in, error := con.Write([]byte(msg));
if error != nil { fmt.Printf("Error sending data: %s, in: %d\n", error, in ); os.Exit(2); }

fmt.Println("Connection OK");

}

what i was trying to do in client  is as soon as user inputs something on console , same is send to the server. So, i did like this :

for inp!="quit" {
    fmt.Scanf("%s",&inp);
_, error := con.Write([]byte(inp));
         if error != nil {
    //to handle errors   
    }

}

But then, it was not sending anything to the server. But don't know why. Write is suppose to write to the server through con object.

Please guide me.
Also , if I want to handle mutiple clients , should the server be using go rountines, if yes , then how.

Thanks for the help.

Regards

Abhinav

Tamás Gulácsi

unread,
Nov 2, 2013, 2:37:32 AM11/2/13
to golan...@googlegroups.com
Maybe not the cause, but do not use error as a variable name, as that is a builti interface already.

Try printing out what you are sending before the send in the client inner loop - fmt.Scanf requires separaor at the end (space or newline).

Reply all
Reply to author
Forward
0 new messages