鉴于Go语言有着强大的多线程能力,所以就写个最简单的socket例子供大家参考。
server.go
-
package main
-
-
import (
-
"fmt"
-
"net"
-
"os"
-
)
-
-
func main() {
-
var (
-
host = "127.0.0.1"
-
port = "8080"
-
remote = host + ":" + port
-
data = make([]byte, 1024)
-
)
-
fmt.Println("Initiating server... (Ctrl-C to stop)")
-
-
lis, err := net.Listen("tcp", remote)
-
defer lis.Close()
-
-
if err != nil {
-
fmt.Println("Error when listen: ", remote)
-
os.Exit(-1)
-
}
-
-
for {
-
var res string
-
conn, err := lis.Accept()
-
if err != nil {
-
fmt.Println("Error accepting client: ", err.Error())
-
os.Exit(0)
-
}
-
-
go func(con net.Conn) {
-
fmt.Println("New connection: ", con.RemoteAddr())
-
for {
-
length, err := con.Read(data)
-
if err != nil {
-
fmt.Printf("Client %v quit.\n", con.RemoteAddr())
-
con.Close()
-
return
-
}
-
res = string(data[0:length])
-
fmt.Printf("%s said: %s\n", con.RemoteAddr(), res)
-
res = "You said:" + res
-
con.Write([]byte(res))
-
}
-
}(conn)
-
}
-
}
client.go
-
package main
-
-
import (
-
"fmt"
-
"net"
-
"os"
-
)
-
-
var str string
-
var msg = make([]byte, 1024)
-
-
func main() {
-
var (
-
host = "127.0.0.1"
-
port = "8080"
-
remote = host + ":" + port
-
)
-
-
con, err := net.Dial("tcp", remote)
-
defer con.Close()
-
-
if err != nil {
-
fmt.Println("Server not found.")
-
os.Exit(-1)
-
}
-
fmt.Println("Connection OK.")
-
-
for {
-
fmt.Printf("Enter a sentence:")
-
fmt.Scanf("%s\n", &str)
-
if str == "quit" {
-
fmt.Println("Communication terminated.")
-
os.Exit(1)
-
}
-
-
in, err := con.Write([]byte(str))
-
if err != nil {
-
fmt.Printf("Error when send to server: %d\n", in)
-
os.Exit(0)
-
}
-
-
length, err := con.Read(msg)
-
if err != nil {
-
fmt.Printf("Error when read from server.\n")
-
os.Exit(0)
-
}
-
str = string(msg[0:length])
-
fmt.Println(str)
-
}
-
}
[转载自:
http://duyizhuo.com/blog/?p=372]
阅读(6539) | 评论(0) | 转发(0) |