tcp server
Node.js
const net = require('net')
function handler(socket) {
socket.write('Received: ')
socket.pipe(socket)
}
const server = net.createServer(handler)
server.listen(3000)
Output
$ echo 'hello' | nc localhost 3000
Received: hello
Go
package main
import (
"bufio"
"net"
)
func handler(conn net.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
return
}
conn.Write([]byte("Received: "))
conn.Write([]byte(message))
}
}
func main() {
listener, err := net.Listen("tcp", ":3000")
if err != nil {
panic(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
panic(err)
}
go handler(conn)
}
}
Output
$ echo 'hello' | nc localhost 3000
Received: hello
当前内容版权归 miguelmota 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 miguelmota .