用Go简单实现网络通信

其余功能可以在这个模型上继续加,比如增加通信人数,实现聊天

server 端

package main

import (
"fmt"
"log"
"net"
"os"
) func broadcaster() { //功能代完善 } func handleCoon(conn net.Conn) {
msg := ""
for {
data := make([]byte,)
msg_read,err := conn.Read(data)
if msg_read == {  //也可以写成 if(msg_read == 0 || err != nil) { }
continue
}else if err != nil {
fmt.Fprintf(os.Stdout,"readmsg err = %v",err)
continue
} msg_read_str := string(data[:msg_read])
if msg_read_str == "quit" {
conn.Write([]byte("Exit..."))
break
} fmt.Println("client msg = ",msg_read_str) fmt.Printf("send to client : ")
fmt.Scan(&msg) conn.Write([]byte(msg))
} fmt.Println("client close")
conn.Close()
} func main() { lis,err := net.Listen("tcp","127.0.0.1:8888")
if err != nil {
log.Fatal(err)
} defer lis.Close()
fmt.Println(lis)
go broadcaster() for {
conn,err := lis.Accept()
if err != nil {
fmt.Fprintf(os.Stdout,"err = %v",err)
continue
} defer conn.Close() go handleCoon(conn)
} client 端
package main

import (
"fmt"
"net"
"os"
) func main() { conn,err := net.Dial("tcp","127.0.0.1:8888")
if err != nil {
fmt.Fprintf(os.Stdout,"err = %v",err)
} defer conn.Close() fmt.Println("connect server sucess") var msg string for {
msg = ""
fmt.Printf("send msg : ")
fmt.Scan(&msg) conn.Write([]byte(msg)) data := make([]byte,)
msg_read,err := conn.Read(data)
if msg_read == {    //和上面一样
fmt.Println("to short for msg")
continue
}else if err != nil {
fmt.Fprintf(os.Stdout,"err = %v",err)
continue
} msg_read_str := string(data[:msg_read]) if msg_read_str == "quit" {
fmt.Println("server close.....")
break
}
fmt.Println("to you msg = ",msg_read_str)
}
}

Go简单聊天-LMLPHP

05-11 22:05