I will install the go language development environment on the development machine of mac OS x.
Go Language Runtime package: http://code.google.com/p/go/downloads/list
Here I choose to install go1.0.3.darwin-amd64.pkg
Click Install on mac, and the running package is automatically installed in/usr/local/go, so that you can run the go command on the command terminal.
Here, I installed the go editor in my xcode application, because my xcode is installed above 4.x.
In/usr/local/go/misc, you can see many editor versions. Here, find the xcode Directory, which is 4, and there is a go4xcode. sh
Enter:
Sudo sh
./Go4xcode. sh
You may report the following errors:
Xcrun: Error: cocould not stat active Xcode path '/Volumes/Xcode/Xcode44-DP7.app/Contents/Developer'. (No such file or directory)
You can see this solution: http://stackoverflow.com/questions/11456918/change-xcrun-developer-path
Use the xcode-select command.
The go runtime package is installed on mac by default. The GOROOT environment variable is not added. You must add a directory named/usr/local/go as the GOROOT, and then execute go4xcode. sh.
Now we reference A socket Communication Example:
Server
Package main
Import (
"Net"
"Fmt"
"Io"
)
Const RECV_BUF_LEN = 1024
Func main (){
Listener, err: = net. Listen ("tcp", "0.0.0.0: 6666") // Listen on port 6666
If err! = Nil {
Panic ("error listening:" + err. Error ())
}
Fmt. Println ("Starting the server ")
For {
Conn, err: = listener. Accept () // Accept the connection
If err! = Nil {
Panic ("Error accept:" + err. Error ())
}
Fmt. Println ("Accepted the Connection:", conn. RemoteAddr ())
Go EchoServer (conn)
}
}
Func EchoServer (conn net. Conn ){
Buf: = make ([] byte, RECV_BUF_LEN)
Defer conn. Close ()
For {
N, err: = conn. Read (buf );
Switch err {
Case nil:
Conn. Write (buf [0: n])
Case io. EOF:
Fmt. Printf ("Warning: End of data: % s \ n", err );
Return
Default:
Fmt. Printf ("Error: Reading data: % s \ n", err );
Return
}
}
}
Client
Package main
Import (
"Fmt"
"Time"
"Net"
)
Const RECV_BUF_LEN = 1024
Func main (){
Conn, err: = net. Dial ("tcp", "127.0.0.1: 6666 ")
If err! = Nil {
Panic (err. Error ())
}
Defer conn. Close ()
Buf: = make ([] byte, RECV_BUF_LEN)
For I: = 0; I <5; I ++ {
// Prepare the string to be sent
Msg: = fmt. Sprintf ("Hello World, % 03d", I)
N, err: = conn. Write ([] byte (msg ))
If err! = Nil {
Println ("Write Buffer Error:", err. Error ())
Break
}
Fmt. Println (msg)
// Receiving string from the server
N, err = conn. Read (buf)
If err! = Nil {
Println ("Read Buffer Error:", err. Error ())
Break
}
Fmt. Println (string (buf [0: n])
// Wait for one second
Time. Sleep (time. Second)
}
}
First run server:
Go run server. go
Then execute the client:
Go run client. go
Back to the server:
After the client information is sent, the end character of EOF is displayed in the server segment.
In addition, execute go build xxx. go to generate a unit executable file in the current directory. Execute./xxx to execute the file.