本文整理汇总了Golang中net.Conn.Write方法的典型用法代码示例。如果您正苦于以下问题:Golang Conn.Write方法的具体用法?Golang Conn.Write怎么用?Golang Conn.Write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net.Conn
的用法示例。
在下文中一共展示了Conn.Write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Exec
// Exec executes the query.
func (c *Command) Exec() (*Response, error) {
resp := &Response{}
var err error
var conn net.Conn
if c.ls.keepConn != nil {
conn = c.ls.keepConn
} else {
// Connect to socket
conn, err = c.dial()
if err != nil {
return nil, err
}
}
if !c.ls.keepalive {
c.ls.keepConn = nil
defer conn.Close()
} else {
c.ls.keepConn = conn
}
// Send command data
cmd, err := c.buildCmd(time.Now())
if err != nil {
return nil, err
}
conn.Write([]byte(cmd))
// You get nothing back from an external command
// no way of knowing if this has worked
return resp, nil
}
示例2: HandleNewMachine
// ROOT ONLY - When we know that there is a new machine pending.
// We need to find it place in out net and send the information about it to our children.
// We also need to create updated chart and send it to children, too.
func (s *Server) HandleNewMachine(socket net.Conn, msg string) {
log.Println("Starting parent search")
DataMap := sip.InterpreteData(sip.ExtractData(msg))
fatherNode, _ := tree.FindSolution(s.Root, -1)
log.Printf("Parent = %s\n", fatherNode.IP)
capacity, _ := strconv.Atoi(DataMap["capacity"])
tree.AddNewChild(fatherNode, tree.NewNode(DataMap["ip"], capacity))
newMes := sip.FND(DataMap["ip"], fatherNode.IP)
if fatherNode.IP == s.Address {
log.Printf("Adding child %s %s\n", s.Address, DataMap["ip"])
s.AddChild(DataMap["ip"])
_, err := socket.Write([]byte(newMes.ToString()))
log.Println(err)
} else {
s.AskChildren(newMes.ToString())
}
s.CreateChart()
time.Sleep(1 * time.Second)
for i := 0; i < s.ChildNumber; i++ {
log.Printf("Sending chart to %s\n", s.Children[i])
SendChart(s.Children[i])
}
}
示例3: handleClient
func handleClient(conn net.Conn) {
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
if err != nil {
return
}
line := string(buf[0:n])
//*******LOGIC*************************************************************************************
m := map[string]string{"google.com": "8.8.8.8", "cedille.etsmtl.ca": "142.137.247.120"}
for key, value := range m {
// for each pair in the map, print key and value
if line == key {
fmt.Println(value)
} else {
fmt.Println("not mapped")
}
}
//*******END OF LOGIC******************************************************************************
_, err2 := conn.Write(buf[0:n])
if err2 != nil {
return
}
}
}
示例4: send
func (this *reqHeader) send(conn net.Conn) error {
buf := this.marshal()
if _, err := conn.Write(buf); err != nil {
return err
}
return nil
}
示例5: ClientHandler
// Creates a new client object for each new connection using the name sent by the client,
// then starts the ClientSender and ClientReader goroutines to handle the IO
func ClientHandler(conn net.Conn) {
inComingChan := make(chan []byte)
outGoingChan := make(chan []byte)
outGoingChanSingle := make(chan []byte)
rndKey := make([]byte, 32)
rand.Read(rndKey)
//Do encryption key exchange
newClient := Client{"GeneralChat", "Anonymous", inComingChan, outGoingChan, outGoingChanSingle, conn, rndKey}
conn.Write(protocolPacker(0x0C, 0xAE, []byte(newClient.Name), []byte(newClient.Room), rndKey))
//Give connect message
//conn.Write(protocolPacker(0x2C, 0xAE, []byte(newClient.Name), []byte(newClient.Room), []byte("BarrensChat Version ")))
//Add client to generalchat
RoomList["GeneralChat"].Clients = append(RoomList["GeneralChat"].Clients, &newClient)
go ClientSender(&newClient) //TODO: change to only 1 go routine.
go ClientReader(&newClient)
go singleClientSender(&newClient)
//outGoingChan <- []byte(name + " has joined the chat")
}
示例6: handleClient
func handleClient(conn net.Conn) {
conn.SetReadDeadline(time.Now().Add(2 * time.Minute)) // 2分钟无接收信息超时
//func (c *TCPConn) SetReadDeadline(t time.Time) error
//func (c *TCPConn) SetWriteDeadline(t time.Time) error
defer conn.Close()
for {
request := make([]byte, 128)
//128 位读取信息
read_len, err := conn.Read(request)
if err != nil {
fmt.Println(err)
break
}
if read_len == 0 {
break // connection already closed by client
} else if string(request) == "timestamp" {
daytime := strconv.FormatInt(time.Now().Unix(), 10)
conn.Write([]byte(daytime))
} else {
daytime := time.Now().String()
conn.Write([]byte(daytime))
}
}
}
示例7: handleIncomingConn
// handles incoming requests
func handleIncomingConn(conn net.Conn, messageChannel chan *GatewayEvent) {
defer conn.Close()
// TODO send an initialization message (see https://github.com/Syncbak-Git/nsca/blob/master/packet.go#L163)
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
n, err := conn.Read(buf)
if err != nil {
Logger().Warning.Println("Error reading incoming request", err.Error())
return
}
// attempt to parse the message
if n < 1024 {
buf = buf[:n]
}
message, err := parseMessage(buf)
// continue down processing pipeline
if err != nil {
Logger().Warning.Println("Failed to parse message", err.Error())
// TODO: determine how to send proper error response
conn.Write([]byte("Message could not be processed."))
} else {
Logger().Trace.Printf("Processing message: %v\n", message)
messageChannel <- newMessageEvent(message)
}
conn.Close()
}
示例8: write
func write(buf []byte, con net.Conn) {
n, err := con.Write(buf)
if err != nil && err.String() == "Timeout() == true" {
com.Log(6, "Write time-out reached. Written "+fmt.Sprint(n)+" bytes.")
}
com.Log(8, "Package sent!")
}
示例9: serveInBlock
func serveInBlock(conn net.Conn, fileName string) {
file, err := os.Open(fileName)
file, err = encryptFile(file, "")
if err != nil {
log.Println("error opening "+fileName, err)
return
}
defer file.Close()
reader := bufio.NewReader(file)
outBuffer := make([]byte, 2048)
for {
// read a chunk
numRead, err := reader.Read(outBuffer)
if err != nil {
log.Println("problem with reader")
log.Println(numRead, err)
break
}
// write that chunk to outgoing request
numSent, err := conn.Write(outBuffer[0:numRead])
log.Println(numRead, "bytes read", numSent, "bytes sent")
}
conn.Close()
}
示例10: readFunction
func readFunction(conn net.Conn, fileName string) {
mutexLock.Lock()
if !Exists(fileName) {
conn.Write([]byte("ERR_FILE_NOT_FOUND\r\n"))
} else {
content, err := ioutil.ReadFile("./" + fileName)
if err == nil {
expTime := fileExpTimeMap[fileName]
var timeLeft float64
if expTime == 0 {
timeLeft = 0
} else {
timeLeft = expTime - timeInSecsNow()
if timeLeft < 0 {
timeLeft = 0
}
}
conn.Write([]byte("CONTENTS " + strconv.FormatInt(fileVersionMap[fileName], 10) +
" " + strconv.Itoa(len(content)) + " " + strconv.FormatFloat(timeLeft, 'f', -1, 64) + " " + "\r\n"))
conn.Write(content)
conn.Write([]byte("\r\n"))
} else {
conn.Write([]byte("ERR_INTERNAL\r\n"))
}
}
mutexLock.Unlock()
}
示例11: PostJoinHandle
// PostJoinHandle implements the handle for the join document (POST).
func PostJoinHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
// INFO(Santiago): Here, we need firstly parse the posted fields, check for "nickclash", if this is the case
// flush the page informing it. Otherwise we add the user basic info and flush the room skeleton
// [TOP/BODY/BANNER]. Then we finally close the connection.
var userData map[string]string
var replyBuffer []byte
userData = rawhttp.GetFieldsFromPost(httpPayload)
if _, posted := userData["user"]; !posted {
newConn.Close()
return
}
if _, posted := userData["color"]; !posted {
newConn.Close()
return
}
preprocessor.SetDataValue("{{.nickname}}", userData["user"])
preprocessor.SetDataValue("{{.session-id}}", "0")
if rooms.HasUser(roomName, userData["user"]) || userData["user"] == rooms.GetAllUsersAlias(roomName) ||
strings.Contains(userData["user"], "<") || strings.Contains(userData["user"], ">") ||
strings.Contains(userData["user"], "<") || strings.Contains(userData["user"], ">") {
replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetNickclashTemplate(roomName)), 200, true)
} else {
rooms.AddUser(roomName, userData["user"], userData["color"], true)
preprocessor.SetDataValue("{{.session-id}}", rooms.GetSessionID(userData["user"], roomName))
replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetSkeletonTemplate(roomName)), 200, true)
rooms.EnqueueMessage(roomName, userData["user"], "", "", "", rooms.GetJoinMessage(roomName), "")
}
newConn.Write(replyBuffer)
newConn.Close()
}
示例12: GetJoinHandle
// GetJoinHandle implements the handle for the join document (GET).
func GetJoinHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
// INFO(Santiago): The form for room joining was requested, so we will flush it to client.
var replyBuffer []byte
replyBuffer = rawhttp.MakeReplyBuffer(preprocessor.ExpandData(roomName, rooms.GetEntranceTemplate(roomName)), 200, true)
newConn.Write(replyBuffer)
newConn.Close()
}
示例13: PostFindHandle
// PostFindHandle implements the handle for the find document (POST).
func PostFindHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
var userData map[string]string
userData = rawhttp.GetFieldsFromPost(httpPayload)
var replyBuffer []byte
if _, posted := userData["user"]; !posted {
replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
} else {
var result string
result = preprocessor.ExpandData(roomName, rooms.GetFindResultsHeadTemplate(roomName))
listing := rooms.GetFindResultsBodyTemplate(roomName)
availRooms := rooms.GetRooms()
user := strings.ToUpper(userData["user"])
if len(user) > 0 {
for _, r := range availRooms {
users := rooms.GetRoomUsers(r)
preprocessor.SetDataValue("{{.find-result-users-total}}", rooms.GetUsersTotal(r))
preprocessor.SetDataValue("{{.find-result-room-name}}", r)
for _, u := range users {
if strings.HasPrefix(strings.ToUpper(u), user) {
preprocessor.SetDataValue("{{.find-result-user}}", u)
result += preprocessor.ExpandData(roomName, listing)
}
}
}
}
result += preprocessor.ExpandData(roomName, rooms.GetFindResultsTailTemplate(roomName))
replyBuffer = rawhttp.MakeReplyBuffer(result, 200, true)
}
newConn.Write(replyBuffer)
newConn.Close()
}
示例14: PubHandle
// PubHandle implements the handle for the room's public directory (GET).
func PubHandle(newConn net.Conn, roomName, httpPayload string, rooms *config.CherryRooms, preprocessor *html.Preprocessor) {
pubdir := rooms.GetPublicDirectory(roomName)
var httpReq string
var spaceNr int
for _, h := range httpPayload {
if h == ' ' {
spaceNr++
}
if h == '\n' || h == '\r' || spaceNr > 1 {
break
}
httpReq += string(h)
}
var replyBuffer []byte
if len(pubdir) == 0 || !strings.HasPrefix(httpReq, "GET /pub/"+pubdir) {
replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
} else {
relativeLocalPath := httpReq[9:]
_, err := os.Stat(relativeLocalPath)
if os.IsNotExist(err) {
replyBuffer = rawhttp.MakeReplyBuffer(html.GetBadAssErrorData(), 404, true)
} else {
replyBuffer = rawhttp.MakeReplyBufferByFilePath(relativeLocalPath, 200, true)
}
}
newConn.Write(replyBuffer)
newConn.Close()
}
示例15: handleConnection
// we create a buffer (output) in order to sort the output
func (stats *ProgramStats) handleConnection(conn net.Conn) {
defer conn.Close()
output := make([]string, 0, len(stats.stats)+2)
output = append(output, fmt.Sprintf("log-shuttle.alltime.drops: %d\n", stats.drops.AllTime()))
output = append(output, fmt.Sprintf("log-shuttle.alltime.lost: %d\n", stats.lost.AllTime()))
stats.Mutex.Lock()
now := time.Now()
output = append(output, fmt.Sprintf("log-shuttle.last.stats.connection: %d\n", stats.lastPoll.Unix()))
output = append(output, fmt.Sprintf("log-shuttle.last.stats.connection.since: %f\n", now.Sub(stats.lastPoll).Seconds()))
stats.lastPoll = now
for name, stream := range stats.stats {
output = append(output, fmt.Sprintf("log-shuttle.%s.count: %d\n", name, stream.Count()))
output = append(output, fmt.Sprintf("log-shuttle.%s.p50: %f\n", name, stream.Query(0.50)))
output = append(output, fmt.Sprintf("log-shuttle.%s.p95: %f\n", name, stream.Query(0.95)))
output = append(output, fmt.Sprintf("log-shuttle.%s.p99: %f\n", name, stream.Query(0.99)))
stream.Reset()
}
stats.Mutex.Unlock()
sort.Strings(output)
for i := range output {
_, err := conn.Write([]byte(output[i]))
if err != nil {
log.Printf("Error writting stats out: %s\n", err)
}
}
}