不一樣語言之間的通訊方式有不少種,這裏我介紹一種最簡單通訊方式,json-rpc。php
Golang自帶json-rpc包,使用起來十分簡單,示例以下,提供一個簡單echo server。golang
package main import ( "fmt" "net" "net/rpc" "net/rpc/jsonrpc" ) type Serve struct { } func (s *Serve) Echo(a *int, r *int) error { *r = 1 return nil } func main() { tcpAddr, err := net.ResolveTCPAddr("tcp", ":9001"); if err != nil { fmt.Println(err) return } l, err := net.ListenTCP("tcp", tcpAddr) if err != nil { fmt.Println(err) return } serve := &Serve{} rpc.Register(serve) for { conn, err := l.Accept() if err != nil { fmt.Println(err) continue } go jsonrpc.ServeConn(conn) } }
php 客戶端代碼,示例以下。json
$conn = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$conn) { return FALSE; } socket_set_option($conn, SOL_SOCKET, SO_SNDTIMEO, array( "sec" => 0, "usec" => 50000 )); $result = socket_connect($conn, '127.0.0.1', 9001); $s = time(); $w = ['id' => time(), 'params' => [1], 'method' => 'Serve.Echo']; socket_write($conn, json_encode($w)); $r = socket_read($conn, 1024); socket_close($conn); echo $r;
就這樣。架構
更多架構、PHP、GO相關踩坑實踐技巧請關注個人公衆號:PHP架構師socket