Go tcp

梦想游戏人
目录:
Go
//server

package main

import "fmt"
import "net"

func recv(conn net.Conn) {
	fmt.Println("new client:", conn.RemoteAddr().String())
	for {

		buffer := make([]byte, 2048)
		len, err := conn.Read(buffer)
		if err != nil {
			fmt.Println(" dis connected ")
			return
		}
		fmt.Println("recv:", string(buffer[0:len]))
		conn.Write([]byte("hi chrome"))
		conn.Close()
		return
	}
}
func main() {
	fmt.Println("start up")
	addr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:80")
	var lis, err2 = net.ListenTCP("tcp", addr)
	if err2 == nil {
	}

	fmt.Println("init socket success")
	for {
		conn, err3 := lis.AcceptTCP()
		if err3 != nil {

		}
		go recv(conn)
	}
}



//client

package main

import (
	"fmt"
	"io/ioutil"
	"net"
	"time"
)

func recv(conn net.Conn) {
	for {
		fmt.Println(conn.RemoteAddr().String())
		var bytes, _ = ioutil.ReadAll(conn)
		fmt.Println("recv:", string(bytes))
	}
}
func main() {
	fmt.Println("start up")
	addr, _ := net.ResolveTCPAddr("tcp4", "127.0.0.1:80")
	conn, _ := net.DialTCP("tcp4", nil, addr)

	fmt.Println("connected success")
	for {
		time.Sleep(1000000000)
		conn.Write([]byte("eeeeeeeeeeeeeeeeeeee"))
	}
}
Scroll Up