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