本文的原文连接是: http://www.jb51.cc/article/p-clygwvee-ber.html 转载请必须注明出处!
1,socket服务
使用golang开发socket服务还是非常简单的。
socket的库都封装好了。
参考文档:
https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/08.1.md
2,简单例子
- package main
-
- import (
- "fmt"
- "net"
- "os"
- "time"
- )
-
- func main() {
- tcpAddr,err := net.ResolveTCPAddr("tcp4",":8080")
- checkError(err)
- listener,err := net.ListenTCP("tcp",tcpAddr)
- checkError(err)
- for {//循环处理
- conn,err := listener.Accept()
- if err != nil {
- continue
- }
- go handleClient(conn)//创建一个goroutinue处理
- }
- }
-
- func handleClient(conn net.Conn) {
- defer conn.Close()
- daytime := time.Now().String()
- conn.Write([]byte(daytime)) // don't care about return value
- // we're finished with this client
- }
- func checkError(err error) {
- if err != nil {
- fmt.Fprintf(os.Stderr,"Fatal error: %s",err.Error())
- os.Exit(1)
- }
- }
通过net.ListenTCP(“tcp”,tcpAddr) 创建一个服务,
然后用for循环,通过listener.Accept() 再创建一个goroutinue处理。
测试,使用telnet测试
- $ telnet 127.0.0.1 8080
- Trying 127.0.0.1...
- Connected to localhost.
- Escape character is '^]'.
- 2015-07-14 17:33:59.602610026 +0800 CSTConnection closed by foreign host.
3,增加交互处理
当客户端输入参数的时候,服务端可以处理。
这里遇到几个问题一个是客户端输入的带回车\r\n要替换掉。
在一个字符串比较用等号即可,但是byte转换字符串长度不一样,需要特殊处理。
- package main
-
- import (
- "net"
- "os"
- "fmt"
- "time"
- "strings"
- )
-
- func main() {
- // println(os.Args[0])
- // println("Hello world!")
-
- tcpAddr,":8080")
- checkError(err, 1)
-
- listener,tcpAddr)
- checkError(err, 2)
-
- for {
- conn,err := listener.Accept()
- if err != nil {
- continue
- }
- go handleClient(conn)
- }
-
- os.Exit(0)
- }
-
- func handleClient(conn net.Conn) {
- conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 设置两分钟超时。
- user_cmd := make([]byte, 128) //设置用户输入的命令
- defer conn.Close()
-
- for {
- read_len,err := conn.Read(user_cmd)
-
- if err != nil {
- fmt.Println(err)
- break
- }
- if read_len == 0 {
- break // connection already closed by client
- }
-
- //fmt.Println(string(user_cmd))
- //fmt.Println(len(string(user_cmd)))//长度是128,而不是time字符串的长度。
- //####################需要特殊处理字符串,找到每一个字符,然后累加。####################
- cmd_str := ""
- for i := 0; i < len(user_cmd); i ++ {
- //println(cmd_str[i])
- if user_cmd[i] == 0 {
- break
- }else {
- cmd_str += string(user_cmd[i])
- }
- }
-
- //替换字符
- cmd_str = strings.Replace(cmd_str,"\r\n","", -1)
-
- if cmd_str == "time" {
- time_now := time.Now().String()
- conn.Write([]byte(time_now))
- }else if cmd_str == "exit" {//退出命令。
- conn.Close()
- }
-
- user_cmd = make([]byte, 128) // clear last read content
- }
- }
-
- func checkError(err error,num int) {
- if err != nil {
- fmt.Fprintf(os.Stderr,"%d) Fail Error:%s",num,err.Error())
- os.Exit(1)
- }
- }
客户端telnet调用:当输入time返回时间,当输入exit关闭连接。
- $ telnet 127.0.0.1 8080
- Trying 127.0.0.1...
- Connected to localhost.
- Escape character is '^]'.
- time
- 2015-07-14 17:44:06.743505631 +0800 CST
- exit
- Connection closed by foreign host.
4,总结
本文的原文连接是: http://www.jb51.cc/article/p-clygwvee-ber.html 转载请必须注明出处!