golang tcp socket - 处理多条消息

我有这个 Go 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: "jan@newmarch.name"},

                      { Kind: "work", Address: "j.newmarch@boxhill.edu.au"}

                     ]

}



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');

});


当年话下
浏览 278回答 2
2回答

米琪卡哇伊

因为您正在获得源源不断的数据流,所以服务器需要知道如何分隔消息。一种方法是使用换行符。我在下面修改了您的代码。转到服务器:包 mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "log"&nbsp; &nbsp; "net")func main() {&nbsp; &nbsp; l, err := net.Listen("tcp", ":1200")&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer l.Close()&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; conn, err := l.Accept()&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; go func(c net.Conn) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message, err := bufio.NewReader(conn).ReadString('\n')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Printf("Error: %+v", err.Error())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; log.Println("Message:", string(message))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }(conn)&nbsp; &nbsp; }}客户端nodejs:var net = require('net');let packet = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Target: { Host: "", Port: "9000" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Name: { Family: "Newmarch", Personal: "Jan" },&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Email: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { Kind: "home", Address: "jan@newmarch.name"},&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; { Kind: "work", Address: "j.newmarch@boxhill.edu.au"}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;]}var client = new net.Socket();client.connect(1200, '0.0.0.0', function() {&nbsp; console.log('Connected');&nbsp; // Send 10 messages&nbsp; for(var i = 0; i < 10; i++) {&nbsp; &nbsp; client.write( (new Buffer(JSON.stringify(packet), 'UTF-8')) );&nbsp; &nbsp; client.write('\n');&nbsp; }&nbsp; client.end();});client.on('data', function(data) {&nbsp; console.log('Received: ' + data);&nbsp; client.destroy();});client.on('close', function() {&nbsp; console.log('Connection closed');});

潇潇雨雨

从io包文档:https://golang.org/pkg/io/#Copy, Copy 函数复制直到遇到 EOF。您不会手动发送 EOF,但关闭连接的客户端会这样做,因此 Copy 功能可以完成复制。您可以使用bufio包来读取带有分隔符的字符串:line,&nbsp;err&nbsp;:=&nbsp;bufio.NewReader(conn).ReadString('\n')在上述情况下,分隔符是换行符。您可以重复使用阅读器在其上重复调用 ReadString 以检索更多消息。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go