Freitag, 11. Dezember 2009

simple server/client

a simple server and client in golang.

server wait for a client and handle him, simple read and write, then close.

client connect to server, write then read to/from server.

server:

package main

import (
. "fmt";
"net";
"os"; "log";
"strings";
)

func test(err os.Error, mesg string) {
if err!=nil {
log.Stderr("SERVER: ERROR: ", mesg);
os.Exit(-1);
} else
log.Stdout("SERVER: OK: ", mesg);
}


func main() {
buf := make([] byte, 1500);

Println("starting server...");

netlisten, err := net.Listen("tcp", "127.0.0.1:9988");
test(err, "Listen");
defer netlisten.Close();

for{
Println("server wait for client ...");
con, err := netlisten.Accept();
test(err, "Accept for client");
Println("client has connect to server");

con.Read(buf);

Println("readed: ", string(buf));

con.Write(strings.Bytes("response from server"));
}
}


client:

package main

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

func test(err os.Error, mesg string) {
if err!=nil {
log.Stderr("CLIENT: ERROR: ", mesg);
os.Exit(-1);
} else
log.Stdout("CLIENT: OK: ", mesg);
}

func main() {
buf := make([] byte, 1500);

Println("starting client");
con, err := net.Dial("tcp", "", "127.0.0.1:9988");
test(err, "dialing");
defer con.Close();
Println("client has connected to server");

con.Write(strings.Bytes("das ist ein test"));

con.Read(buf);

Println("readed: ", string(buf));
}

Keine Kommentare:

Kommentar veröffentlichen