我有這樣的圍棋TCP套接字golang TCP套接字 - 處理多個消息
package main
import (
"fmt"
"io"
"log"
"net"
"bytes"
)
func main() {
l, err := net.Listen("tcp", ":1200")
if err != nil {
log.Fatal(err)
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
log.Fatal(err)
}
go func(c net.Conn) {
var buf bytes.Buffer
io.Copy(&buf, c)
fmt.Println("total size:", buf.Len())
s := buf.String()
println(s)
c.Close()
}(conn)
}
}
接受的消息,將其轉換爲字符串,並顯示它,但如果連接不被客戶關閉,我不能請參閱預期的服務器上顯示的消息
如何從客戶端發送多條消息而無需關閉客戶端連接(由客戶端)?
在這裏,客戶端的NodeJS
var net = require('net');
let packet = {
Target: { Host: "", Port: "9000" },
Name: { Family: "Newmarch", Personal: "Jan" },
Email: [
{ Kind: "home", Address: "[email protected]"},
{ Kind: "work", Address: "[email protected]"}
]
}
var client = new net.Socket();
client.connect(1200, '0.0.0.0', function() {
console.log('Connected');
client.write((new Buffer(JSON.stringify(packet), 'UTF-8')));
client.end();
//client.write('\n');
});
client.on('data', function(data) {
console.log('Received: ' + data);
client.destroy();
});
client.on('close', function() {
console.log('Connection closed');
});
感謝valeriano cossu
作爲答案中提到,你必須以某種方式打破你的消息。 TCP本身是一種流媒體協議,而不是基於數據包的協議。 –