Go TCP

    这是一个go开发的tcp列子, 只是一个简单, 因为没有使用多线程, 只能接受客户端的数据,然后将数据发给客户端就退出了, 好了, 上代码:

代码结构如下
go-tcp/
├── bin
│   └── main
├── pkg
└── src
    ├── main.go
    └── server
        └── tcpserver.go

4 directories, 3 files
main.go代码
package main

import (
	"server"
	"log"
)

func main (){
	//server := new(server.TCPServer)
	//0:8080 = 相当于127.0.0.1:8080
	var s *server.TCPServer = server.NewTCPServer("0:8080")
	log.Println( (*s).Host, (s).Port)
}
tcpserver.go
package server

import (
	"log"
	"net"
)

type TCPServer struct {
	Host string
	Port int
	conn net.Conn
}

func NewTCPServer(address string) *TCPServer {
	server := new(TCPServer)
	//设置监听IP和端口
	addr, err := net.ResolveTCPAddr("tcp4", address)
	server.Host, server.Port =  addr.IP.String() , addr.Port
	//listen
	listener, err := net.ListenTCP("tcp4", addr)
	if err != nil {
		log.Fatal("listenTCP ERROR:", err)
	}

	//accept
	conn, err := listener.Accept()
	if err != nil {
		log.Fatal(err)
	}
	//缓冲区
	buf := make([]byte, 100)
	//读取数据
	cont, err := conn.Read(buf)
	if err == nil && cont > 0 {
		server.conn = conn
		//接受数据
		(*server).reciver(string(buf))
	}else{
		log.Println("read err")
	}
	return server
}

func (this TCPServer) reciver(data string) {
	log.Printf("=>%s", data)
	this.send(data)
}

func (this TCPServer) send(data string) {
	log.Printf("<=%s", data)
	//发送数据给客户端
	this.conn.Write([]byte(data))
}
编译代码
GOPATH=`pwd` go build -o bin/main src/main.go
启动服务
./bin/main
telnet连上服务器, 并且写入数据,回车
gaojie@gaojie:/media/Java/android/workspace$ telnet 0 8080
Trying 0.0.0.0...
Connected to 0.
Escape character is '^]'.
你好啊
你好啊
Connection closed by foreign host.
服务器则显示如下,就退出了.
2013/10/06 10:18:25 =>你好啊

2013/10/06 10:18:25 <=你好啊

2013/10/06 10:18:25 0.0.0.0 8080

你可能感兴趣的:(tcp,Go)