Last active
November 11, 2022 10:51
-
-
Save jdx/7bb72900ff063bb23cef099410e558d7 to your computer and use it in GitHub Desktop.
basic IPC example connecting node and golang together with unix socket (named pipe)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"io" | |
"log" | |
"net" | |
"time" | |
) | |
func reader(r io.Reader) { | |
buf := make([]byte, 1024) | |
for { | |
n, err := r.Read(buf[:]) | |
if err != nil { | |
return | |
} | |
println("client got:", string(buf[0:n])) | |
} | |
} | |
func main() { | |
c, err := net.Dial("unix", "/tmp/foo.sock") | |
if err != nil { | |
log.Fatal("dial error", err) | |
} | |
defer c.Close() | |
go reader(c) | |
for { | |
msg := "hi" | |
_, err := c.Write([]byte(msg)) | |
if err != nil { | |
log.Fatal("write error:", err) | |
break | |
} | |
println("client sent:", msg) | |
time.Sleep(1e9) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const net = require('net') | |
const fs = require('fs') | |
try { | |
// remove existing socket if exists | |
fs.unlinkSync('/tmp/foo.sock') | |
} catch {} | |
net.createServer() | |
.listen('/tmp/foo.sock', () => { | |
console.log('server listening') | |
}) | |
.on('connection', socket => { | |
console.log('client connected') | |
socket.setEncoding('utf8') | |
socket.on('data', data => { | |
console.log(`server received: ${data}`) | |
socket.write(data.toUpperCase()) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment