本文整理汇总了Golang中github.com/pebbe/zmq4.Socket类的典型用法代码示例。如果您正苦于以下问题:Golang Socket类的具体用法?Golang Socket怎么用?Golang Socket使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Socket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: bind
func bind(socket *zmq.Socket, transport string, address string, port int) {
endpoint := fmt.Sprintf("%s://%s:%d", transport, address, port)
err := socket.Bind(endpoint)
if err != nil {
die("failed binding %s: %s", endpoint, err.Error())
}
}
示例2: sendError
func sendError(socket *zmq.Socket, req *Request, err error) {
// Response envelope
resp := &Response{
Error: &Response_Error{},
}
if req != nil {
resp.UUID = req.UUID
}
// If error is a zrpc error
if zrpcErr, ok := err.(zrpcError); ok {
resp.StatusCode = proto.Uint32(uint32(zrpcErr.GetStatusCode()))
resp.Error.Message = proto.String(zrpcErr.GetMessage())
} else {
// Default to internal error
resp.StatusCode = proto.Uint32(uint32(http.StatusInternalServerError))
resp.Error.Message = proto.String(err.Error())
}
// Encode the response
buf, protoErr := proto.Marshal(resp)
if protoErr != nil {
glog.Error(protoErr)
return
}
// Send the response
if _, err := socket.SendBytes(buf, 0); err != nil {
glog.Error(err)
}
}
示例3: SendReply
// SendReply will send the reply back to the connected reply proxy
func SendReply(r *http.Response, body string, repsock *zmq.Socket) {
rep := &messages.Reply{StatusCode: r.StatusCode, Body: body, Headers: r.Header}
reps := rep.String()
fmt.Printf("[PRIVATE] sending %d bytes or \n----\n%s\n-----\n", len(reps), reps)
repsock.Send(reps, 0)
fmt.Printf("[PRIVATE] sent %d bytes\n", len(reps))
}
示例4: r
func r(replier *zmq.Socket) {
for {
got, _ := replier.Recv(0)
log.Println("Received", got)
replier.Send(`{"jsonrpc":"2.0","id":"youpi","result":{"name":"test","hostname":"localtest","protocol":"test","port":0}}`, 0)
}
}
示例5: receieve
func receieve(socketrep *zmq.Socket, s Server) {
var d database
d.Map = make(map[int]*mydetails)
go d.statemachinecommit(s)
for {
fmt.Println("tcp://127.0.0.1:7001")
msg, err := socketrep.RecvBytes(0)
fmt.Println("recived")
if err != nil {
fmt.Println(err)
}
var req request
json.Unmarshal(msg, &req)
fmt.Println("parsing----------------------------------------------------------------------------------------")
fmt.Println(s.leaderid)
fmt.Println("parsing")
fmt.Println(req)
resp := d.parse(req, s)
fmt.Println(resp)
message, _ := json.Marshal(resp)
socketrep.SendBytes(message, 0)
}
}
示例6: New
func New(id int, f string) Cluster {
var myid int
var peer [MAX_SERVER]int
var cluster [MAX_SERVER]*zmq.Socket
var mycluster *zmq.Socket
var no_of_p int
file, _ := ioutil.ReadFile(f)
var jsontype jsonobject
json.Unmarshal(file, &jsontype)
myid = id
no_of_p = jsontype.Object.Buffer_size
for i := 0; i < jsontype.Object.Buffer_size; i++ {
if jsontype.Object.Peers[i].Id != myid {
peer[i] = jsontype.Object.Peers[i].Id
cluster[i], _ = zmq.NewSocket(zmq.PUSH)
cluster[i].Connect("tcp://" + jsontype.Object.Peers[i].Host)
} else {
mycluster, _ = zmq.NewSocket(zmq.PULL)
mycluster.SetIdentity(string(id))
a := strings.Split(jsontype.Object.Peers[i].Host, ":")
mycluster.Bind("tcp://*:" + a[1])
}
}
return Cluster{myid: id, peer: peer, no_of_peer: no_of_p, my_cluster: mycluster, cluster: cluster, inbox: make(chan *Envelope, BUFFER_LENGTH_IN), outbox: make(chan *Envelope, BUFFER_LENGTH_OUT)}
}
示例7: send
// This is simple send function here i communicate with raft using simple request-response socket and ask to raft their status
// like phase of raft and we can also close raft server using this function.
// Here msg :- 1 means msg for ask phase of server and msg:- 0 means close the raft server
func send(msg string, requester_C *zmq.Socket) string {
// Decoding of phse receive by type 0 msg is 0 :- Follower, 1:- Candidate, 2:- Leader
// By default phase :- "3" means no response from server and server is close
requester_C.Send(msg, 0)
phase := "3"
if msg == "0" {
return "0"
}
phase, _ = requester_C.Recv(0)
type1 := s.Split(phase, " ")[0]
value := s.Split(phase, " ")[1]
if type1 == "-1" {
if value == "0" {
phase = "Follower"
} else if value == "1" {
phase = "Candidate"
} else if value == "2" {
phase = "Leader"
}
} else if type1 == "-2" {
leaderId, _ = strconv.Atoi(value)
} else if type1 == "0" {
leaderId, _ = strconv.Atoi(s.Split(phase, " ")[2])
msg_index, _ := strconv.Atoi(value)
send(message[msg_index], requester[leaderId-1])
return "0"
} else {
}
return phase
}
示例8: RecMsgFromPeers
func RecMsgFromPeers(s *zmq.Socket, ser Servernode) {
var e Envelope
for {
msg, err := s.RecvMessage(0)
a1 := strings.Split(msg[0], "&{")
a2 := strings.Split(a1[1], " ")
pid, _ := strconv.Atoi(a2[0])
mid, _ := strconv.Atoi(a2[1])
msgid := int64(mid)
text := ""
for b := 2; b < len(a2); b++ {
text = text + " " + a2[b]
}
text1 := text[1:]
msgtext := strings.Split(text1, "}")[0]
e.Pid = pid
e.MsgId = msgid
e.Msg = msgtext
go QueueInbox(ser, e, ser.Inbox())
if err != nil {
break
}
s.SendMessage(msg)
}
}
示例9: run
func (c *WorkerConnection) run(socket *zmq.Socket) {
defer socket.Close()
socket.SetRcvtimeo(c.activeTimeout)
for {
select {
case <-c.quit:
close(c.wait)
return
case request := <-c.requestChannel:
if _, err := socket.SendMessage(request); err != nil {
log.Println("Failed to send request:", err)
}
case request := <-c.connectionChan:
go c.handleConnectionRequest(socket, request)
default:
message, err := socket.RecvMessageBytes(0)
if err != nil {
// Needed to yield to goroutines when GOMAXPROCS is 1.
// Note: The 1.3 preemptive scheduler doesn't seem to work here,
// so this is still required.
runtime.Gosched()
break
}
socket.SetRcvtimeo(c.activeTimeout)
go c.handleResponse(message)
}
}
}
示例10: Send
// Send sends marshaled data through 0mq socket.
func (b *Binary) Send(socket *zmq.Socket) (err error) {
frame, err := b.Marshal()
if err != nil {
return err
}
socType, err := socket.GetType()
if err != nil {
return err
}
// If we're sending to a ROUTER, we send the routingID first
if socType == zmq.ROUTER {
_, err = socket.SendBytes(b.routingID, zmq.SNDMORE)
if err != nil {
return err
}
}
// Now send the data frame
_, err = socket.SendBytes(frame, zmq.SNDMORE)
if err != nil {
return err
}
// Now send any frame fields, in order
_, err = socket.SendBytes(b.Address, zmq.SNDMORE)
_, err = socket.SendBytes(b.Content, 0)
return err
}
示例11: readMessage
func (k *kernelRunner) readMessage(socket *zmq.Socket) (*message, []string, error) {
parts, err := socket.RecvMessage(0)
if err != nil {
return nil, nil, err
}
return deserializeMessage(parts, []byte(k.connInfo.Key))
}
示例12: receiveMessage
/****************************************************************
Receiving Message from all Servers
****************************************************************/
func receiveMessage(recSockets *zmq.Socket, conn *Connection) {
for {
select {
// Stopping Go Routine
case _, _ = <-conn.stopGoRoutine:
return
default:
recSockets.SetRcvtimeo(500 * time.Millisecond)
msg, err := recSockets.Recv(0)
if err == nil {
msg_array := strings.Split(msg, ":")
msg_seq := msg_array[0]
isLeader := msg_array[1]
leaderId, _ := strconv.Atoi(msg_array[2])
count, _ := strconv.Atoi(isLeader)
// Added the LeaderCount if the response belongs to corresponding request
if strconv.Itoa(conn.attempt) == msg_seq {
conn.recvCount += 1
conn.leaders += count
if leaderId != 0 {
conn.leaderId = leaderId
}
}
}
}
}
}
示例13: recv
// Receives marshaled data from 0mq socket.
func recv(socket *zmq.Socket, flag zmq.Flag) (t Transit, err error) {
// Read all frames
frames, err := socket.RecvMessageBytes(flag)
if err != nil {
return nil, err
}
sType, err := socket.GetType()
if err != nil {
return nil, err
}
var routingId []byte
// If message came from a router socket, first frame is routingId
if sType == zmq.ROUTER {
if len(frames) <= 1 {
return nil, errors.New("no routingId")
}
routingId = frames[0]
frames = frames[1:]
}
t, err = Unmarshal(frames...)
if err != nil {
return nil, err
}
if sType == zmq.ROUTER {
t.SetRoutingId(routingId)
}
return t, err
}
示例14: createSendAndReceivingSocket
/************************************************************
Creates Sockets for Sending and Receiving purpose
*************************************************************/
func createSendAndReceivingSocket(configFile string, selfPort int) ([]*zmq.Socket, *zmq.Socket) {
file, e := ioutil.ReadFile("./" + configFile)
if e != nil {
fmt.Printf("Raft Test File error: %v\n", e)
os.Exit(1)
}
var jsontype jsonobject
json.Unmarshal(file, &jsontype)
elementCount := len(jsontype.Server)
sendConnections := make([]*zmq.Socket, elementCount)
tempId := 0
for _, value := range jsontype.Server {
sendConnections[tempId], _ = zmq.NewSocket(zmq.PUSH)
sendConnections[tempId].Connect("tcp://localhost:" + strconv.Itoa(value.Port_Num+1))
tempId++
}
var receiveConnection *zmq.Socket
receiveConnection, _ = zmq.NewSocket(zmq.PULL)
receiveConnection.Bind("tcp://*:" + strconv.Itoa(selfPort))
return sendConnections, receiveConnection
}
示例15: NewEventSubSocketHandler
// NewEventSubSocketHandler returns a function that handles event notifications
func NewEventSubSocketHandler(eventSubSocket *zmq4.Socket) func(zmq4.State) error {
var nodeIDMap map[string]uint32
var err error
if nodeIDMap, err = centraldb.GetNodeIDMap(); err != nil {
fog.Critical("centraldb.GetNodeIDMap() failed %s", err)
}
return func(_ zmq4.State) error {
var err error
var ok bool
var webWriterStart msg.WebWriterStart
var timestamp time.Time
var sourceNodeID uint32
marshalledMessage, err := eventSubSocket.RecvMessage(0)
if err != nil {
return fmt.Errorf("RecvMessage %s", err)
}
// the 0th part should be the topic, we skip that
err = json.Unmarshal([]byte(marshalledMessage[1]), &webWriterStart)
if err != nil {
return fmt.Errorf("Unmarshal %s", err)
}
if webWriterStart.MessageType != "web-writer-start" {
return fmt.Errorf("unknown message type '%s'",
webWriterStart.MessageType)
}
timestamp, err = tools.ParseTimestampRepr(webWriterStart.TimestampRepr)
if err != nil {
return fmt.Errorf("unable to parse %s %s",
webWriterStart.TimestampRepr, err)
}
sourceNodeID, ok = nodeIDMap[webWriterStart.SourceNodeName]
if !ok {
return fmt.Errorf("unknown source_node_name %s",
webWriterStart.SourceNodeName)
}
fog.Debug("cancel-segments-from-node %s", webWriterStart.SourceNodeName)
// cancel all all segment rows
// * from a specifiic source node
// * are in active status
// * with a timestamp earlier than the specified time.
// This is triggered by a web server restart
stmt := nodedb.Stmts["cancel-segments-from-node"]
if _, err = stmt.Exec(sourceNodeID, timestamp); err != nil {
return fmt.Errorf("cancel-segments-from-node %s", err)
}
return nil
}
}