2016-10-06 37 views
2

我已經有一個Go TCP服務器接受連接,我想一次回顯1個字節的消息,我看不到一個方法來獲得net.Conn使用net.Conn.Write發送一個字節net.Conn去

c.Write([]byte(b)) cannot convert b (type byte) to type []byte

c.Write(b) cannot use b (type byte) as type []byte in argument to c.Write

回答

5

一個io.Writer總是接受[]byte作爲參數來發送一個字節。使用一個1字節的長字節片。你試過的([]byte(b))是將單個字節轉換爲字節片。相反,創建一個元素的字節片與b作爲唯一的元素:

n, err := c.Write([]byte{b}) 
+0

乾杯:)我會在10分鐘內 –

-1

使用b[i:i+1]創建一個字節片:

s := "Hello world!" 
b := []byte(s) 

for i:=0; i<len(s); i++ { 
    c.Write(b[i:i+1]) 
} 
+0

接受這個爲什麼我爲此得到-1?請添加評論並解釋! – md2perpe