用go搭建tcp服务器,实在很方便,调用C写的底层应用也很方便,有些特别注意的地方,红色标记,以便以后查阅

package main

/*

#cgo LDFLAGS: -Llib -lwiringPi //编译时链接wiringPi库
#include <stdio.h>
#include <unistd.h>
#include "wiringPi.h"
void ctest(){
        wiringPiSetup();
        pinMode(2,OUTPUT);
        while(1){
        digitalWrite(2,HIGH);
        sleep(1);
        digitalWrite(2,LOW);
        sleep(1);
}

}
*/
import "C"
import (
"fmt"
"time"
"net"
)

func main(){
        fmt.Println("hello,i am GO")
        go  C.ctest()
        time.Sleep(time.Second)
 fmt.Println("Starting the server ...")
    // 创建 listener
    listener, err := net.Listen("tcp", "192.168.1.166:50000")
    if err != nil {
        fmt.Println("Error listening", err.Error())
        return //终止程序
    }
    // 监听并接受来自客户端的连接
    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Error accepting", err.Error())
            return // 终止程序
        }
        go doServerStuff(conn)
    }
}

func doServerStuff(conn net.Conn) {
    for {
        buf := make([]byte, 512)
        len, err := conn.Read(buf)
        if err != nil {
            fmt.Println("Error reading", err.Error())
            return //终止程序
        }
        fmt.Printf("Received data: %v\n", string(buf[:len]))
         conn.Write([]byte("hello client!"))
}
}