最近用lua写了服务端,为了测试在网上找了用go写的客户端收发信息的内容,这个比较容易就在此记录下。
main函数内容
var msg_read_chan chan bytes.Buffer
var msg_writer_chan chan bytes.Buffer
func init() {
}
func main(){
fmt.Println("Start connect...")
conn,err :=net.Dial("tcp","127.0.0.1:8000")
util.CheckErrorOrExit(err)
defer conn.Close()
//读写channel
msg_read_chan = make(chan bytes.Buffer,32)
msg_writer_chan = make(chan bytes.Buffer,32)
go nws.ReadRoutine(&conn,&msg_read_chan)
go nws.WriteRoutine(&conn,&msg_writer_chan)
handler_msg_routine(&msg_read_chan)
}
func handler_msg_routine(msg_chan *chan bytes.Buffer) {
for{
fmt.Println("waiting msg ...")
msg_raw := <-msg_read_chan
msg :=(*bytes.Buffer)(&msg_raw)
fmt.Println("got msg:",msg)
}
}
读写操作
//读操作
func ReadRoutine(conn *net.Conn,reader *chan bytes.Buffer) {
msg_feedback := bytes.NewBuffer(nil)
var buf [512]byte
for{
transferred, err :=(*conn).Read(buf[0:])
util.CheckErrorOrExit(err)
msg_feedback.Write(buf[0:transferred])
*reader <- *msg_feedback
fmt.Println("reseted")
//处理完一个msg,重置
msg_feedback.Reset()
}
}
func WriteRoutine(conn *net.Conn,writer *chan bytes.Buffer) {
for{
msg:= <- *writer
msg2 := (bytes.Buffer)(msg)
(*conn).Write(msg2.Bytes())
}
}
网友评论