本文整理汇总了Golang中bufio.Writer.Flush方法的典型用法代码示例。如果您正苦于以下问题:Golang Writer.Flush方法的具体用法?Golang Writer.Flush怎么用?Golang Writer.Flush使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bufio.Writer
的用法示例。
在下文中一共展示了Writer.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: requestsSender
func requestsSender(w *bufio.Writer, requests <-chan tasker, responses chan<- tasker, c net.Conn, done *sync.WaitGroup) {
defer done.Done()
defer w.Flush()
defer close(responses)
scratchBuf := make([]byte, 0, 1024)
for {
var t tasker
var ok bool
// Flush w only if there are no pending requests.
select {
case t, ok = <-requests:
default:
w.Flush()
t, ok = <-requests
}
if !ok {
break
}
if !t.WriteRequest(w, &scratchBuf) {
t.Done(false)
break
}
responses <- t
}
}
示例2: draft75handshake
/*
Handhake described in (soon obsolete)
draft-hixie-thewebsocket-protocol-75.
*/
func draft75handshake(resourceName, host, origin, location, protocol string, br *bufio.Reader, bw *bufio.Writer) (err os.Error) {
bw.WriteString("GET " + resourceName + " HTTP/1.1\r\n")
bw.WriteString("Upgrade: WebSocket\r\n")
bw.WriteString("Connection: Upgrade\r\n")
bw.WriteString("Host: " + host + "\r\n")
bw.WriteString("Origin: " + origin + "\r\n")
if protocol != "" {
bw.WriteString("WebSocket-Protocol: " + protocol + "\r\n")
}
bw.WriteString("\r\n")
bw.Flush()
resp, err := http.ReadResponse(br, "GET")
if err != nil {
return
}
if resp.Status != "101 Web Socket Protocol Handshake" {
return ErrBadStatus
}
if resp.Header["Upgrade"] != "WebSocket" ||
resp.Header["Connection"] != "Upgrade" {
return ErrBadUpgrade
}
if resp.Header["Websocket-Origin"] != origin {
return ErrBadWebSocketOrigin
}
if resp.Header["Websocket-Location"] != location {
return ErrBadWebSocketLocation
}
if protocol != "" && resp.Header["Websocket-Protocol"] != protocol {
return ErrBadWebSocketProtocol
}
return
}
示例3: outputResults
func (r Resolver) outputResults(w *bufio.Writer, results gresults) {
var zip, city, state, stateName, county, country, countryName string
var latitude, longitude float32
var comp addressComponent
var err error
for _, res := range results.Results {
if comp, err = res.findAddressComponent(zipType); err == nil {
zip = comp.LongName
}
if comp, err = res.findAddressComponent(cityType); err == nil {
city = comp.LongName
}
if comp, err = res.findAddressComponent(countyType); err == nil {
county = comp.LongName
}
if comp, err = res.findAddressComponent(stateType); err == nil {
state = strings.ToUpper(comp.ShortName)
stateName = comp.LongName
}
if comp, err = res.findAddressComponent(countryType); err == nil {
country = strings.ToUpper(comp.ShortName)
countryName = comp.LongName
}
latitude = res.Geometry.Location.Lat
longitude = res.Geometry.Location.Lng
}
w.WriteString(fmt.Sprintf("%v,\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",\"%v\",%v,%v\n", country, zip, city, state, stateName, county, countryName, latitude, longitude))
w.Flush()
}
示例4: NewStreamReader
// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// Close must be called on the returned reader after all the required data
// has been read. Otherwise goroutine leak may occur.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.ReadCloser {
pc := fasthttputil.NewPipeConns()
pw := pc.Conn1()
pr := pc.Conn2()
var bw *bufio.Writer
v := streamWriterBufPool.Get()
if v == nil {
bw = bufio.NewWriter(pw)
} else {
bw = v.(*bufio.Writer)
bw.Reset(pw)
}
go func() {
defer func() {
if r := recover(); r != nil {
defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
}
}()
sw(bw)
bw.Flush()
pw.Close()
streamWriterBufPool.Put(bw)
}()
return pr
}
示例5: writer
func (conn *Connection) writer() {
var w *bufio.Writer
var err error
for {
var packet []byte
select {
case packet = <-conn.packets:
default:
if w = conn.w; w != nil {
if err := w.Flush(); err != nil {
conn.closeConnection(err)
}
}
select {
case packet = <-conn.packets:
case <-conn.control:
return
}
}
if packet == nil {
return
}
if w = conn.w; w == nil {
if _, w, err = conn.createConnection(); err != nil {
return
}
}
if err := write(w, packet); err != nil {
conn.closeConnection(err)
continue
}
}
}
示例6: sendUpdates
func (t *TcpPlayer) sendUpdates(w *bufio.Writer, wg *sync.WaitGroup) {
defer wg.Done()
enc := json.NewEncoder(w)
lastTurnSent := -1
for update := range t.update {
t.stateL.Lock()
t.state = update
t.stateL.Unlock()
if update.Turn == lastTurnSent {
continue
}
if err := enc.Encode(update); err != nil {
t.l.Errorf("[TCP] sending update to player, %v", err)
return
}
if _, err := w.WriteRune('\n'); err != nil {
t.l.Errorf("[TCP] sending EOL to player, %v", err)
return
}
if err := w.Flush(); err != nil {
t.l.Errorf("[TCP] flushing update to player, %v", err)
return
}
lastTurnSent = update.Turn
}
}
示例7: WriteProto
func WriteProto(wr *bufio.Writer, proto *Proto) (err error) {
// write
if err = binary.Write(wr, binary.BigEndian, uint32(rawHeaderLen)+uint32(len(proto.Body))); err != nil {
return
}
if err = binary.Write(wr, binary.BigEndian, rawHeaderLen); err != nil {
return
}
if err = binary.Write(wr, binary.BigEndian, proto.Ver); err != nil {
return
}
if err = binary.Write(wr, binary.BigEndian, proto.Operation); err != nil {
return
}
if err = binary.Write(wr, binary.BigEndian, proto.SeqId); err != nil {
return
}
if proto.Body != nil {
log.Debug("cipher body: %v", proto.Body)
if err = binary.Write(wr, binary.BigEndian, proto.Body); err != nil {
return
}
}
err = wr.Flush()
return
}
示例8: writeErrorResponseHeader
func writeErrorResponseHeader(w *bufio.Writer, opcode uint8, status uint16, opaque uint32) error {
header := resHeadPool.Get().(ResponseHeader)
header.Magic = MagicResponse
header.Opcode = opcode
header.KeyLength = uint16(0)
header.ExtraLength = uint8(0)
header.DataType = uint8(0)
header.Status = status
header.TotalBodyLength = uint32(0)
header.OpaqueToken = opaque
header.CASToken = uint64(0)
if err := writeResponseHeader(w, header); err != nil {
resHeadPool.Put(header)
return err
}
if err := w.Flush(); err != nil {
resHeadPool.Put(header)
return err
}
metrics.IncCounterBy(common.MetricBytesWrittenRemote, resHeaderLen)
resHeadPool.Put(header)
return nil
}
示例9: deleteGroup
func deleteGroup(r *bufio.Reader, w *bufio.Writer, args []string, thisUser *utils.User) (err error) {
if len(args) < 2 {
fmt.Println("Not enough arguments for call to group-remove:")
fmt.Println("Format should be: delete-group GID")
return nil
}
err = w.WriteByte(24)
w.Flush()
if err != nil {
return err
}
w.WriteString(args[1] + "\n")
w.Flush()
// get success (1) or fail (2)
success, _ := r.ReadByte()
if success != 1 {
fmt.Println("You cannot remove this group. Does it exist/are you the owner?")
return err
}
fmt.Println("Removed: " + args[1])
return err
}
示例10: authTCP
// auth for goim handshake with client, use rsa & aes.
func (server *Server) authTCP(rr *bufio.Reader, wr *bufio.Writer, ch *Channel) (subKey string, heartbeat time.Duration, err error) {
var p *Proto
// WARN
// don't adv the cli proto, after auth simply discard it.
if p, err = ch.CliProto.Set(); err != nil {
return
}
if err = server.readTCPRequest(rr, p); err != nil {
return
}
if p.Operation != define.OP_AUTH {
log.Warn("auth operation not valid: %d", p.Operation)
err = ErrOperation
return
}
if subKey, ch.RoomId, heartbeat, err = server.operator.Connect(p); err != nil {
log.Error("operator.Connect error(%v)", err)
return
}
p.Body = nil
p.Operation = define.OP_AUTH_REPLY
if err = server.writeTCPResponse(wr, p); err != nil {
log.Error("[%s] server.sendTCPResponse() error(%v)", subKey, err)
}
err = wr.Flush()
return
}
示例11: writeSuccessResponseHeader
func writeSuccessResponseHeader(w *bufio.Writer, opcode uint8, keyLength, extraLength,
totalBodyLength int, opaque uint32, flush bool) error {
header := resHeadPool.Get().(ResponseHeader)
header.Magic = MagicResponse
header.Opcode = opcode
header.KeyLength = uint16(keyLength)
header.ExtraLength = uint8(extraLength)
header.DataType = uint8(0)
header.Status = StatusSuccess
header.TotalBodyLength = uint32(totalBodyLength)
header.OpaqueToken = opaque
header.CASToken = uint64(0)
if err := writeResponseHeader(w, header); err != nil {
resHeadPool.Put(header)
return err
}
if flush {
if err := w.Flush(); err != nil {
resHeadPool.Put(header)
return err
}
}
metrics.IncCounterBy(common.MetricBytesWrittenRemote, resHeaderLen)
resHeadPool.Put(header)
return nil
}
示例12: testWriteMatch
func testWriteMatch(t *testing.T, obj writeObject, expected string) {
var buf *bytes.Buffer = bytes.NewBuffer(nil)
var wr *bufio.Writer = bufio.NewWriter(buf)
var err error
err = obj.write(wr)
if err != nil {
t.Errorf("Error: %#v", err)
return
}
err = wr.Flush()
if err != nil {
t.Errorf("Error: %#v", err)
return
}
var bExpected []byte = []byte(expected)
var bActual []byte = buf.Bytes()
if !bytes.Equal(bExpected, bActual) {
t.Errorf("Expected: %#v, got: %#v", string(bExpected), string(bActual))
return
}
}
示例13: readFile
func readFile(path string) {
var w *bufio.Writer = bufio.NewWriter(os.Stdout)
defer w.Flush()
fmt.Fprintf(w, "read file start: %s\n", path)
file, err := os.OpenFile(path, os.O_RDONLY, 0666) // 打开文件
if err != nil {
fmt.Printf("open file err: %v\n", err)
return
}
defer file.Close() // 延时关闭文件
var buff []byte = make([]byte, 1024)
var r *bufio.Reader = bufio.NewReader(file)
for {
n, _ := r.Read(buff)
if n <= 0 {
fmt.Fprintf(w, "read file end: %s %d\n", path, n)
return
}
w.Write(buff[0:n])
}
}
示例14: marshalText
func marshalText(w io.Writer, pb Message, compact bool) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte("<nil>"))
return nil
}
var bw *bufio.Writer
ww, ok := w.(writer)
if !ok {
bw = bufio.NewWriter(w)
ww = bw
}
aw := &textWriter{
w: ww,
complete: true,
compact: compact,
}
// Dereference the received pointer so we don't have outer < and >.
v := reflect.Indirect(val)
if err := writeStruct(aw, v); err != nil {
return err
}
if bw != nil {
return bw.Flush()
}
return nil
}
示例15: HandshakeSample
func HandshakeSample(c net.Conn, br *bufio.Reader, bw *bufio.Writer, timeout time.Duration) (err error) {
defer func() {
if r := recover(); r != nil {
err = r.(error)
}
}()
// Send C0+C1
err = bw.WriteByte(0x03)
c1 := CreateRandomBlock(RTMP_SIG_SIZE)
for i := 0; i < 8; i++ {
c1[i] = 0
}
bw.Write(c1)
err = bw.Flush()
CheckError(err, "Handshake() Flush C0+C1")
// Read S0+S1+S2
s0, err := br.ReadByte()
CheckError(err, "Handshake() Read S0")
if s0 != 0x03 {
return errors.New(fmt.Sprintf("Handshake() Got S0: %x", s0))
}
s1 := make([]byte, RTMP_SIG_SIZE)
_, err = io.ReadAtLeast(br, s1, RTMP_SIG_SIZE)
CheckError(err, "Handshake() Read S1")
bw.Write(s1)
err = bw.Flush()
CheckError(err, "Handshake() Flush C2")
_, err = io.ReadAtLeast(br, s1, RTMP_SIG_SIZE)
CheckError(err, "Handshake() Read S2")
return
}