Golang实现一个简单的网络编程

Server:

package main

import (
	"fmt"
	"io"
	"net"
)

func handle(conn net.Conn) {
	defer conn.Close()
	ip := conn.RemoteAddr().String()
	fmt.Printf("new client:%s\n", ip)
	for {
		buff := make([]byte, 128)
		bufflen, err := conn.Read(buff)
		if err == io.EOF {
			fmt.Printf("%s close\n", ip)
			return
		}
		if err != nil {
			fmt.Printf("%s read err:%s\n", ip, err.Error())
			continue
		}
		if bufflen > 0 {
			fmt.Printf("%s recv:%s\n", ip, string(buff[0:bufflen]))
			conn.Write(buff[0:bufflen])
		}
	}
}

func main() {
	listen, err := net.Listen("tcp", "127.0.0.1:9999")
	if err != nil {
		fmt.Printf("tcp listen err:%s\n", err.Error())
		return
	}
	defer listen.Close()
	fmt.Println("tcp listen 127.0.0.1:9999")
	for {
		conn, err := listen.Accept()
		if err != nil {
			continue
		}
		go handle(conn)
	}
}

Client:

package main

import (
	"fmt"
	"io"
	"net"
	"strconv"
	"time"
)

var ch = make(chan int, 2)

func CreatConn(num int) {
	conn, err := net.Dial("tcp", "127.0.0.1:9999")
	if err != nil {
		fmt.Printf("dial err:%s\n", err.Error())
		return
	}
	defer conn.Close()
	str := "hello,i am " + strconv.Itoa(num)
	for {
		time.Sleep(time.Second * 5)

		_, err = conn.Write([]byte(str))
		if err != nil {
			fmt.Printf("write err:%s\n", err.Error())
		} else {
			fmt.Printf("send:%s\n", str)
		}

		buff := make([]byte, 128)
		datalen, err := conn.Read(buff)
		if err == io.EOF {
			fmt.Println("server close")
			ch <- 1
			return
		}
		if err == nil && datalen > 0 {
			fmt.Printf("recv:%s\n", string(buff[:datalen]))
		}
	}
}

func main() {
	for i := 1; i <= 2; i++ {
		go CreatConn(i)
	}
	<-ch
	<-ch
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值