dongquanjie9328 2018-06-12 13:05
浏览 63
已采纳

如何将切片与字符串进行比较?

package main

import (
    "fmt"
    "net"
)

func main() {

    msg := make([]byte, 1024)

    //Basic variables
    port := ":2002"
    protocol := "udp"

    //Build the address
    myaddr, err := net.ResolveUDPAddr(protocol, port)
    if err != nil {
        fmt.Println("Wrong Address")
        return
    }

    //Output
    fmt.Println("Reading " + protocol + " from " + myaddr.String())

    //Create the connection
    connection, err := net.ListenUDP(protocol, myaddr)
    if err != nil {
        fmt.Println(err)
    }

    //receive msg
    for {
        _, useraddr, err := connection.ReadFromUDP(msg)
        fmt.Println("msg from :", useraddr)

        if err != nil {
            fmt.Printf("Some error  %v", err)
            continue
        }
        go sendResponse(connection, useraddr)
    }
}

This is my UDP server, I'm making a game. So I want, if the client send "let's play", the server to run the go sendresponse function. If it's not "let's play " it will not run.

I think I should compare msg but I don't know how. Thank you :)

  • 写回答

1条回答 默认 最新

  • duan0424 2018-06-12 14:00
    关注

    Perhaps, something like this:

    //receive msg
    msg := make([]byte, 1024)
    for {
        n, useraddr, err := connection.ReadFromUDP(msg[:cap(msg)])
        msg = msg[:n]
        fmt.Println("msg from :", useraddr)
        if err != nil {
            fmt.Printf("Some error  %v", err)
            continue
        }
        if string(msg) == "let's play" {
            go sendResponse(connection, useraddr)
        }
    }
    

    The expression msg[:cap(msg)] sets the msg buffer length to its full capacity.

    The statement msg = msg[:n] sets the msg buffer length to the actual length read.

    The string(msg) expression converts the msg type []byte to type string for the comparison.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示