gotcpc/sserverclient学习笔记-创新互联
server1:
package main
import (
"fmt"
"net"
)
func main() {
l, err := net.Listen("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
fmt.Println("服务器等待客户端连接")
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
}
defer conn.Close()
fmt.Println("客户端建立连接 ")
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
conn.Write(buf[:n])
}
client1:
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
defer conn.Close()
conn.Write([]byte("are you ready"))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(buf[:n]))
}
sever2:
package main
import (
"fmt"
"io"
"net"
"runtime"
"strings"
)
func process(conn net.Conn) {
// io.Copy(conn, conn)
buf := make([]byte, 4096)
for {
n, err := conn.Read(buf)
if err != nil {
if err == io.EOF {
fmt.Println("客户端断开连接")
runtime.Goexit()
} else {
fmt.Println(err)
runtime.Goexit()
}
//break
}
fmt.Println("接收到消息:", string(buf[:n]))
conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
//fmt.Println(strings.ToUpper(string(buf[:n])))
}
}
func main() {
l, err := net.Listen("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err)
continue
}
defer conn.Close()
fmt.Println(conn.RemoteAddr())
go process(conn)
}
}
client2:
package main
import (
"bufio"
"fmt"
"net"
"os"
"strings"
)
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:9876")
if err != nil {
fmt.Println(err)
}
defer conn.Close()
for {
//strs :=""
// fmt.Scanln(&strs) 空格有问题
//strs := make([]byte, 4096)
//n, err := os.Stdin.Read(strs)
fmt.Println("请输入要发送的消息:")
str, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
fmt.Println(err)
}
str = strings.TrimSpace(str)
//fmt.Println("发送前", , "展示")
//fmt.Println("a", str, "b")
if str == "Q" {
fmt.Println("接收到退出命令,退出客户端")
break
}
conn.Write([]byte(str))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
break
}
defer conn.Close()
fmt.Println("接收到消息:", string(buf[:n]))
}
}
创新互联www.cdcxhl.cn,专业提供香港、美国云服务器,动态BGP最优骨干路由自动选择,持续稳定高效的网络助力业务部署。公司持有工信部办法的idc、isp许可证, 机房独有T级流量清洗系统配攻击溯源,准确进行流量调度,确保服务器高可用性。佳节活动现已开启,新人活动云服务器买多久送多久。
当前名称:gotcpc/sserverclient学习笔记-创新互联
文章来源:http://cdiso.cn/article/diegcc.html