Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Forked from zhujo01/client.go
Created Aug 9, 2011
Embed
What would you like to do?
TLS echo server and client
package main
import (
"crypto/tls"
"io"
"log"
)
func main() {
conn, err := tls.Dial("tcp", "127.0.0.1:8000", nil)
if err != nil {
log.Fatalf("client: dial: %s", err)
}
defer conn.Close()
log.Println("client: connected to: ", conn.RemoteAddr())
state := conn.ConnectionState()
log.Println("client: handshake: ", state.HandshakeComplete)
log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)
message := "Hello\n"
n, err := io.WriteString(conn, message)
if err != nil {
log.Fatalf("client: write: %s", err)
}
log.Printf("client: wrote %q (%d bytes)", message, n)
reply := make([]byte, 256)
n, err = conn.Read(reply)
log.Printf("client: read %q (%d bytes)", string(reply[:n]), n)
log.Print("client: exiting")
}
package main
import (
"crypto/rand"
"crypto/tls"
"log"
"net"
"os"
"time"
)
func main() {
cert, err := tls.LoadX509KeyPair("certs/ssl-cert-snakeoil.pem", "certs/ssl-cert-snakeoil.key")
if err != nil {
log.Fatalf("server: loadkeys: %s", err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}}
now := time.Seconds()
config.Time = func() int64 { return now }
config.Rand = rand.Reader
service := "0.0.0.0:8000"
listener, err := tls.Listen("tcp", service, &config)
if err != nil {
log.Fatalf("server: listen: %s", err)
}
log.Print("server: listening")
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("server: accept: %s", err)
break
}
log.Printf("server: accepted from %s", conn.RemoteAddr())
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer conn.Close()
buf := make([]byte, 512)
for {
log.Print("server: conn: waiting")
n, err := conn.Read(buf)
if err != nil {
if err != os.EOF {
log.Printf("server: conn: read: %s", err)
}
break
}
log.Printf("server: conn: echo %q\n", string(buf[:n]))
n, err = conn.Write(buf[:n])
log.Printf("server: conn: wrote %d bytes", n)
if err != nil {
log.Printf("server: write: %s", err)
break
}
}
log.Println("server: conn: closed")
}
2011/08/09 13:48:55 server: listening
2011/08/09 13:48:57 server: accepted from 127.0.0.1:41689
2011/08/09 13:48:57 server: conn: waiting
2011/08/09 13:48:57 client: connected to: 127.0.0.1:8000
2011/08/09 13:48:57 client: handshake: true
2011/08/09 13:48:57 client: mutual: true
2011/08/09 13:48:57 client: wrote "Hello\n" (6 bytes)
2011/08/09 13:48:57 server: conn: echo "Hello\n"
2011/08/09 13:48:57 server: conn: wrote 6 bytes
2011/08/09 13:48:57 server: conn: waiting
2011/08/09 13:48:57 client: read "Hello\n" (6 bytes)
2011/08/09 13:48:57 client: exiting
2011/08/09 13:48:57 server: conn: closed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment