【发布时间】:2011-11-07 03:40:45
【问题描述】:
我在 Golang 中遇到了一些字符串问题。似乎它们没有被移交给另一个函数。
func Sendtext(ip string, port string, text string) (err int) {
targ := ip + ":" + port
raddr,e := net.ResolveTCPAddr("tcp",targ)
if e != nil {
os.Stdout.WriteString(e.String()+"\n")
return 1
}
conn,e := net.DialTCP("tcp",nil,raddr)
if e != nil {
os.Stdout.WriteString(e.String()+"\n")
return 1
}
conn.Write([]byte(text))
mess := make([]byte,1024)
conn.Read(mess)
message := string(mess)
conn.Close()
if message[0] == 'a' {
return 0
} else {
return 1
}
return 0
}
func main() {
os.Stdout.WriteString("Will send URL: ")
url := GetURL()
os.Stdout.WriteString(url + "\n\n")
_, port, pass, ip := browserbridge_config.ReadPropertiesFile()
os.Stdout.WriteString("sending this url to " + ip + ":" + port + "\n")
message := url + "\n" + pass + "\n"
os.Stdout.WriteString("\nsending... ")
e := Sendtext(ip, port, message)
if e != 0 {
os.Stdout.WriteString("ERROR\n")
os.Exit(e);
}
os.Stdout.WriteString("DONE\n")
}
和我的配置阅读器:
func ReadConfigFile(filename string) (browsercommand string, port string, pass string, ip string) {
// set defaults
browsercommand = "%u"
port = "7896"
pass = "hallo"
ip = "127.0.0.1"
// open file
file, err := os.Open(filename)
if err != nil {
os.Stdout.WriteString("Error opening config file. proceeding with standard config...")
return
}
// Get reader and buffer
reader := bufio.NewReader(file)
for {
part,_,err := reader.ReadLine()
if err != nil {
break
}
buffer := bytes.NewBuffer(make([]byte,2048))
buffer.Write(part)
s := strings.ToLower(buffer.String())
if strings.Contains(s,"browsercommand=") {
browsercommand = strings.Replace(s,"browsercommand=","",1)
} else {
if strings.Contains(s,"port=") {
port = strings.Replace(s,"port=","",1)
} else {
if strings.Contains(s,"password=") {
pass = strings.Replace(s,"password=","",1)
} else {
if strings.Contains(s,"ip=") {
ip = strings.Replace(s,"ip=","",1)
}
}
}
}
}
return
}
这个程序的输出:
Will send URL: test.de
sending this url to 192.168.2.100:7896
sending...
dial tcp 192.168.2.1:0: connection refused
ERROR
(192.168.2.1 是网关)
我在 Sendtext 的顶部尝试了 os.Stdout.WriteString(targ) 或 os.Stdout.WriteString(ip),但没有输出。
关于它的令人困惑的事情:昨天它工作 xD(在我将 ReadConfig 迁移到它自己的 .go 文件之前)
希望你能帮我解决这个问题...
锡拉尔
更新:
正如 PeterSO 所说,问题不在于琴弦的交接 我的第一个猜测,它必须是字符串到 TCPAddr 的转换,这是真的,但它似乎是字符串的问题,而不是网络库的问题。 我刚刚添加 ip = "192.168.2.100" 端口 = "7896" 在调用 Sendtext 之后,这很有帮助...(至少在用户需要设置自定义 ip/port 之前...)
我知道当我决定从 goconf (http://code.google.com/p/goconf/) 切换到我自己的时,问题就出现了。这就是我认为问题出在 ReadProperties() 函数的原因。
我还意识到 strconv.Atoi(port) 返回 0(解析“7896”:无效参数) 当我使用具有已实现(不可更改)配置的服务器和客户端,然后让客户端从配置文件中读取密码时,密码比较失败。当我还在代码中正确设置密码时(不读取文件),它可以工作。
我现在真的不知道该怎么办......有什么想法吗?
【问题讨论】: