首先复习一下go的基本语法
1:变量定义
val 变量 变量类型
val v1 int val v2 string val v3 [10]int //定义一个int10的数组 val v4 map[string] string //定义一个字典 key为string value也为string val v5 func(a int) int //v5指向一个函数
可以更简单一些,根据数据推断类型,如下:
v6 := 90
v7 := "hello china"
匿名变量 _,_,name := GetName()
如果调用一个方法返回多个变量,有些变量不使用,可以用——代替
常量 const mark = 1<<3
go server
package main
/*
*go server
*can be serve as chat,game,file trans server
*also can be serve as proxy server
*surpport protocal :http tcp udp ftp https sock5 and so on
*
*************************************************************************/
import (
"fmt"
"io"
"log"
)
import "net"
const addr = "127.0.0.1:1080"
const bufferSize = 4096
const maxConn = 1000
type bundle struct {
clientNO int64 //current client num
clients map[string]serverClient //store client in the map,key:client name,value: serverClient
}
func (s bundle) init() {
}
func (s bundle) startNewClient(clientName string, client serverClient) {
s.clients[clientName] = client
s.clientNO++
client.startProcess()
}
type serverClient struct {
clientName string //client username
Conn net.Conn
//send chan []byte
//reply io.Writer
}
//process client data
func (client serverClient) startProcess() {
data := make([]byte, bufferSize)
n, _ := io.ReadFull(client.Conn, data)
if n > 0 {
fmt.Println(string(data[0:n]))
}
client.Conn.Write([]byte("hello "))
}
//start server,when accept ,let gorountine to process
func startServer() {
b := new(bundle)
b.clients = make(map[string]serverClient)
a, err := net.ResolveTCPAddr("tcp", addr)
if err != nil {
log.Fatal(err)
}
l, err2 := net.ListenTCP("tcp", a)
if err2 != nil {
log.Fatal(err2)
}
for {
c, err3 := l.Accept()
if err3 != nil {
log.Fatal(err3)
}
fmt.Print("new client from :")
fmt.Println(c.RemoteAddr())
ch := serverClient{"1", c}
go b.startNewClient(c.RemoteAddr().String(), ch)
}
}
func main() {
fmt.Println("start server")
startServer()
}
go client
package main
import (
"fmt"
"io"
"log"
)
import "net"
const svrAddr = "127.0.0.1:1080"
const clientAddr = "127.0.0.1:2090"
const bufferSize = 4096
type clientBundle struct {
conn net.Conn
}
func startClient(ch chan int) {
conn, err := net.Dial("tcp", svrAddr)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
b := clientBundle{conn}
//conn.Write([]byte("hello server"))
io.WriteString(conn, "sfsf")
//io.Writer.
b.processRead()
}
func (b clientBundle) processRead() {
//data := make([]byte, bufferSize)
//n, _ := io.ReadFull(b.conn, data)
//if n > 0 {
// fmt.Println(data[:n])
//}
}
func main() {
fmt.Println("start client")
for {
conns := make(chan int)
startClient(conns)
}
//<-conns
fmt.Println("finish send")
}