本文整理汇总了Golang中net.TCPConn.Write方法的典型用法代码示例。如果您正苦于以下问题:Golang TCPConn.Write方法的具体用法?Golang TCPConn.Write怎么用?Golang TCPConn.Write使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.TCPConn
的用法示例。
在下文中一共展示了TCPConn.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: runReads
//
// A TCP 'echo' example.
// Demonstrates using a timeout, and a 'graceful' shutdown if one occurs.
// 'Tested' using 'telnet localhost 45678'
//
func runReads(tcpConn *net.TCPConn) bool {
br := bufio.NewReader(tcpConn)
for {
// Set a timeout value, which needs to be set before each and every read.
d := time.Duration(30 * 1e9) // 30 seconds
w := time.Now() // from now
w = w.Add(d)
tcpConn.SetReadDeadline(w) // Set the deadline
//
buffer, err := br.ReadBytes('\n') // '\n' is delimiter
// If the read times out, this prints something like:
// Error = read tcp 127.0.0.1:57609: resource temporarily unavailable
if err != nil {
fmt.Printf("Error = %v\n", err)
return false
// panic("wtf04")
}
//
fmt.Printf("Bytes Read: %d\n", len(buffer))
var data = string(buffer)
fmt.Printf("Data Read: |%q|\n", data)
// This is now an 'echo' example.
out := "echo: " + data
tcpConn.Write([]byte(out))
// The \r in this data from telnet is a bit surprising ...
if data == "quit\r\n" {
fmt.Println("Breaking....")
break
}
}
return true
}
示例2: listenForMoveRequests
func listenForMoveRequests(conn *net.TCPConn) {
listenServe := make(chan []uint8)
easynet.TieConnToChannel(conn, listenServe)
for data := range listenServe {
r := new(ttypes.BotMoveRequest)
err := json.Unmarshal(data, r)
easynet.DieIfError(err, "JSON error")
if r.Kill {
fmt.Printf("Bot on %s received kill signal\n", os.Args[0])
os.Exit(0)
}
fmt.Printf("Bot at %d, %d received messages: %v\n", r.YourX, r.YourY, r.Messages)
fmt.Printf(" Sees other bots: %v\n", r.OtherBots)
//Do something
response := new(ttypes.BotMoveResponse)
if r.YourY < 5 {
response.MoveDirection = "up"
} else if r.YourY > 5 {
response.MoveDirection = "down"
}
// response.BroadcastMessage = fmt.Sprintf("'I am %v at %d, %d'", os.Args[0], r.YourX, r.YourY)
responseString, err := json.Marshal(response)
easynet.DieIfError(err, "JSON marshal error")
conn.Write(responseString)
}
}
示例3: pipe
func (p *proxy) pipe(src, dst *net.TCPConn, powerCallback common.Callback) {
//data direction
islocal := src == p.lconn
//directional copy (64k buffer)
buff := make([]byte, 0xffff)
for {
n, err := src.Read(buff)
if err != nil {
p.err("Read failed '%s'\n", err)
return
}
b := buff[:n]
//show output
if islocal {
b = getModifiedBuffer(b, powerCallback)
n, err = dst.Write(b)
} else {
//write out result
n, err = dst.Write(b)
}
if err != nil {
p.err("Write failed '%s'\n", err)
return
}
}
}
示例4: send
func send(tcpconn *net.TCPConn, rsp *Response) (err error) {
Len := uint32(PkgLenSize) + uint32(len(rsp.Head)) + uint32(len(rsp.Body))
Hlen := uint16(Uint16Size) + uint16(len(rsp.Head))
data := make([]byte, 0, int(Len)) // len:0, cap:Len; TODO(zog): cache
buf := bytes.NewBuffer(data) // TODO(zog): 复用
binary.Write(buf, binary.BigEndian, Len)
binary.Write(buf, binary.BigEndian, Hlen)
buf.Write(rsp.Head)
buf.Write(rsp.Body)
if debug {
glog.Infof("sent bytes to %s, len: %d",
tcpconn.RemoteAddr().String(), len(buf.Bytes()))
glog.Flush()
}
tcpconn.SetDeadline(time.Now().Add(100 * time.Millisecond))
if _, err = tcpconn.Write(buf.Bytes()); err != nil {
return err
}
if debug {
glog.Infof("sent data(len:%d): %v", buf.Len(), buf.Bytes())
glog.Flush()
}
return nil
}
示例5: WithClient
func (hs *SimpleHandshake) WithClient(conn *Conn) error {
var iorw *net.TCPConn = conn.IoRw
c0c1 := make([]byte, 1537)
conn.Logger.Info("read c0c1 from conn, size=%v", len(c0c1))
if _, err := io.ReadFull(iorw, c0c1); err != nil {
conn.Logger.Error("read c0c1 failed, err is %v", err)
return err
}
conn.Logger.Info("read c0c1 ok")
if c0c1[0] != 0x03 {
conn.Logger.Error("rtmp plain required 0x03, actual is %#x", c0c1[0])
return RtmpPlainRequired
}
conn.Logger.Info("check rtmp plain protocol ok")
// use bytes buffer to write content.
s0s1s2 := bytes.NewBuffer(make([]byte, 0, 3073))
// plain text required.
binary.Write(s0s1s2, binary.BigEndian, byte(0x03))
// s1 time
binary.Write(s0s1s2, binary.BigEndian, int32(time.Now().Unix()))
// s1 time2 copy from c1
if _, err := s0s1s2.Write(c0c1[1:5]); err != nil {
conn.Logger.Error("copy c0c1 time to s0s1s2 failed, err is %v", err)
return err
}
// s1 1528 random bytes
s0s1s2Random := make([]byte, 1528)
RandomGenerate(conn.Rand, s0s1s2Random)
if _, err := s0s1s2.Write(s0s1s2Random); err != nil {
conn.Logger.Error("fill s1 random bytes failed, err is %v", err)
return err
}
// if c1 specified, copy c1 to s2.
// @see: https://github.com/winlinvip/simple-rtmp-server/issues/46
if _, err := s0s1s2.Write(c0c1[1:1537]); err != nil {
conn.Logger.Error("copy c1 to s1 failed, err is %v", err)
return err
}
conn.Logger.Info("generate s0s1s2 ok, buf=%d", s0s1s2.Len())
if written, err := iorw.Write(s0s1s2.Bytes()); err != nil {
conn.Logger.Error("send s0s1s2 failed, written=%d, err is %v", written, err)
return err
}
conn.Logger.Info("send s0s1s2 ok")
c2 := make([]byte, 1536)
conn.Logger.Info("read c2 from conn, size=%v", len(c2))
if _, err := io.ReadFull(iorw, c2); err != nil {
conn.Logger.Error("read c2 failed, err is %v", err)
return err
}
conn.Logger.Info("read c2 ok")
return nil
}
示例6: sendMessage
func sendMessage(hostName string, portNumber int, msg []byte) {
tcpAddr, err := net.ResolveTCPAddr("tcp4", net.JoinHostPort(hostName, strconv.Itoa(portNumber)))
checkError(err)
var conn *net.TCPConn
for {
conn, err = net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
switch e := err.(type) {
case (*net.OpError):
if e.Err.Error() == "connection refused" {
return
}
default:
fmt.Println(err)
}
} else {
break
}
}
_, err = conn.Write(msg)
checkError(err)
conn.Close()
return
}
示例7: readRemoteLoop
func readRemoteLoop(client, remote *net.TCPConn, stopChan chan<- bool) {
defer func() {
stopChan <- true
}()
addr := client.RemoteAddr()
for {
var buf [4096]byte
nr, err := remote.Read(buf[:])
if err != nil && err != os.EOF {
log.Printf("%v: Failed to read from the remote: %v", addr, err)
return
}
start := 0
for start < nr {
nw, err := client.Write(buf[start:nr])
if err != nil && err != os.EOF {
log.Printf("%v: Failed to write to the client: %v", addr, err)
return
}
start += nw
}
}
}
示例8: pipeThenClose
func pipeThenClose(src, dst *net.TCPConn, finishChannel chan bool) {
defer func() {
src.CloseRead()
dst.CloseWrite()
finishChannel <- true
}()
buf := asocks.GetBuffer()
defer asocks.GiveBuffer(buf)
for {
src.SetReadDeadline(time.Now().Add(60 * time.Second))
n, err := src.Read(buf)
if n > 0 {
data := buf[0:n]
encodeData(data)
if _, err := dst.Write(data); err != nil {
break
}
}
if err != nil {
break
}
}
}
示例9: SendToConn
func SendToConn(data []byte, conn *net.TCPConn, path *big.Int) {
// making variable for combining send data
var (
err tree_lib.TreeError
path_len_data = make([]byte, 4)
msg_len_data = make([]byte, 4)
path_data = path.Bytes()
path_len = uint32(len(path_data))
buf = bytes.Buffer{}
)
err.From = tree_lib.FROM_SEND_TO_CONN
binary.LittleEndian.PutUint32(path_len_data, path_len)
binary.LittleEndian.PutUint32(msg_len_data, path_len+uint32(len(data))+uint32(4))
buf.Write(msg_len_data)
buf.Write(path_len_data)
buf.Write(path_data)
buf.Write(data)
if conn != nil {
_, err.Err = conn.Write(buf.Bytes())
if !err.IsNull() {
tree_log.Error(err.From, fmt.Sprintf("Error sending data to path [%s]", path.String()), err.Error())
}
}
buf.Reset()
}
示例10: pipe
func (p *Proxy) pipe(src, dst *net.TCPConn) {
//data direction
islocal := src == p.lconn
//directional copy (64k buffer)
buff := make([]byte, 0xffff)
for {
n, err := src.Read(buff)
if err != nil {
p.err("Read failed '%s'\n", err)
return
}
b := buff[:n]
//show output
n, err = dst.Write(b)
if err != nil {
p.err("Write failed '%s'\n", err)
return
}
if islocal {
p.sentBytes += uint64(n)
} else {
p.receivedBytes += uint64(n)
}
}
}
示例11: session
func session(conn *net.TCPConn) {
fmt.Println("here")
var buf [2048]byte
code := 0
for {
t := time.Now().Add(time.Millisecond * 100)
conn.SetReadDeadline(t)
n, err := conn.Read(buf[:])
e, ok := err.(net.Error)
if err != nil && ok && !e.Timeout() {
fmt.Println(err)
break
}
if n > 0 {
process(conn, buf[:n])
} else {
msg := fmt.Sprintf("%v", code)
code++
conn.Write([]byte(msg))
}
}
fmt.Println("session ended")
}
示例12: handleRequest
func handleRequest(conn *net.TCPConn, request *vmessio.VMessRequest, input <-chan []byte, finish chan<- bool) {
defer close(finish)
encryptRequestWriter, err := v2io.NewAesEncryptWriter(request.RequestKey[:], request.RequestIV[:], conn)
if err != nil {
log.Error("VMessOut: Failed to create encrypt writer: %v", err)
return
}
buffer, err := request.ToBytes(v2hash.NewTimeHash(v2hash.HMACHash{}), v2math.GenerateRandomInt64InRange)
if err != nil {
log.Error("VMessOut: Failed to serialize VMess request: %v", err)
return
}
// Send first packet of payload together with request, in favor of small requests.
payload, open := <-input
if open {
encryptRequestWriter.Crypt(payload)
buffer = append(buffer, payload...)
_, err = conn.Write(buffer)
if err != nil {
log.Error("VMessOut: Failed to write VMess request: %v", err)
return
}
v2net.ChanToWriter(encryptRequestWriter, input)
}
return
}
示例13: tcpWorker
func tcpWorker(conn *net.TCPConn, server string) {
go handleReader(conn, server)
pkg := &ProtoPkg{
Header: new(ProtoHeader),
Body: []byte("I am a good boy"),
}
pkg.Header.Version = Version
pkg.Header.Cmd = 111
// fmt.Println(pkg, pkgData)
for {
for i := 0; i < 10; i++ {
seq = atomic.AddUint32(&seq, 1)
pkg.Header.Seq = seq
seqInfo := &SeqInfo{
t: time.Now(),
server: server,
}
seqMap[seq] = seqInfo
pkgData := Pack(pkg)
conn.Write(pkgData)
}
checkTimeout()
time.Sleep(100 * time.Millisecond)
}
}
示例14: writeLoop
func writeLoop(conn *net.TCPConn) {
in := bufio.NewReader(os.Stdin)
for {
line, _ := in.ReadString('\n')
conn.Write(strings.Bytes(line))
}
}
示例15: readloop
func readloop(conn *net.TCPConn, clist *[]ChanPair, controlc chan chan string) {
output := make(chan string, 2048)
input := make(chan string, 2048)
controlc <- output
controlc <- input
address := conn.RemoteAddr()
player := parsing.NewPlayer(address.String())
for {
b := make([]byte, 4096)
n, err := conn.Read(b[:])
data := b[:n]
if err != nil {
fmt.Println(err)
}
select {
case str := <-input:
conn.Write([]uint8(str))
default:
}
if len(string(data)) == 0 {
fmt.Println("PARTING:", address.String())
conn.Close()
return
}
conn.Write(parsing.Parse(player, string(data), output))
}
}