前端之家收集整理的这篇文章主要介绍了
golang 使用unixsocket交换数据 socket,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package utils
import (
"fmt"
"net"
"os"
"time"
)
type UnixSocket struct {
filename string
bufsize int
handler func(string) string
}
func NewUnixSocket(filename string,size ...int) *UnixSocket {
size1 := 10480
if size != nil {
size1 = size[0]
}
us := UnixSocket{filename: filename,bufsize: size1}
return &us
}
func (this *UnixSocket) createServer() {
os.Remove(this.filename)
addr,err := net.ResolveUnixAddr("unix",this.filename)
if err != nil {
panic("Cannot resolve unix addr: " + err.Error())
}
listener,err := net.ListenUnix("unix",addr)
defer listener.Close()
if err != nil {
panic("Cannot listen to unix domain socket: " + err.Error())
}
fmt.Println("Listening on",listener.Addr())
for {
c,err := listener.Accept()
if err != nil {
panic("Accept: " + err.Error())
}
go this.HandleServerConn(c)
}
}
func (this *UnixSocket) HandleServerConn(c net.Conn) {
defer c.Close()
buf := make([]byte,this.bufsize)
nr,err := c.Read(buf)
if err != nil {
panic("Read: " + err.Error())
}
result := this.HandleServerContext(string(buf[0:nr]))
_,err = c.Write([]byte(result))
if err != nil {
panic("Writes Failed.")
}
}
func (this *UnixSocket) SetContextHandler(f func(string) string) {
this.handler = f
}
func (this *UnixSocket) HandleServerContext(context string) string {
if this.handler != nil {
return this.handler(context)
}
now := time.Now().String()
return now
}
func (this *UnixSocket) StartServer() {
this.createServer()
}
func (this *UnixSocket) ClientSendContext(context string) string {
addr,this.filename)
if err != nil {
panic("Cannot resolve unix addr: " + err.Error())
}
c,err := net.DialUnix("unix",nil,addr)
if err != nil {
panic("DialUnix Failed.")
}
_,err = c.Write([]byte(context))
if err != nil {
panic("Writes Failed.")
}
buf := make([]byte,err := c.Read(buf)
if err != nil {
panic("Read: " + err.Error())
}
return string(buf[0:nr])
}