go开发桌面应用源码_go Socket_golang Socket_golang开发桌面应用源码_go客户端服务端

客户端代码:

注:go get github.com/lxn/walk

package main

import (
"github.com/lxn/walk"
. "github.com/lxn/walk/declarative"
"net"
)

const (
IP = "127.0.0.1:8888"
)

func main() {
var mw *walk.MainWindow
var uname, pwd *walk.LineEdit

(MainWindow{
AssignTo: &mw,
Title: "织梦多站点管理系统",
MinSize: Size{218, 170},
Size: Size{218, 170},
MaxSize: Size{218, 170},
Layout: VBox{},

Children: []Widget{

Label{
Text: "织梦多站点管理系统",
Font: Font{
PointSize: 10,
Family: "微软雅黑",
},
},

LineEdit{
AssignTo: &uname,
MinSize: Size{0, 25},
CueBanner: "用户名",
Font: Font{
PointSize: 10,
Family: "微软雅黑",
},
},
LineEdit{
AssignTo: &pwd,
MinSize: Size{0, 25},
PasswordMode: true,
CueBanner: "密码",
Font: Font{
PointSize: 10,
Family: "微软雅黑",
},
},
HSplitter{
Children: []Widget{
CheckBox{
Text: "记住密码",
},
CheckBox{
Text: "自动登陆",
},
},
},

HSplitter{
Children: []Widget{
PushButton{

Text: "登陆",
MinSize: Size{0, 30},
OnClicked: func() {

if uname.Text() == "" {
walk.MsgBox(mw, "错误", "请输入您的用户名!", walk.MsgBoxIconInformation)
return
} else if pwd.Text() == "" {
walk.MsgBox(mw, "错误", "请输入您的密码!", walk.MsgBoxIconInformation)
return
}

//链接socket发送数据
connectServer(mw, uname.Text(), pwd.Text())

},
},
PushButton{
Text: "取消",
MinSize: Size{0, 30},
OnClicked: func() { mw.Close() },
},
},
},
},
}).Run()
}

//链接socket发送数据
func connectServer(mw *walk.MainWindow, uname, pwd string) {

buf := make([]byte, 1024)

connect, err := net.Dial("tcp", IP)
if err != nil {
walk.MsgBox(mw, "错误", "服务器连接错误!", walk.MsgBoxIconInformation)
return
}
connect.Write([]byte(uname + "," + pwd))
c, err := connect.Read(buf)
walk.MsgBox(mw, "错误", string(buf[0:c]), walk.MsgBoxIconInformation)
defer connect.Close()

}

 

 

服务端代码:

package main

import (
"fmt"
"net"
)

const (
ADDR = "127.0.0.1"
PORT = 8888
)

var exit chan bool

func main() {

exit = make(chan bool)

ip := net.ParseIP(ADDR)
adr := net.TCPAddr{ip, PORT, ""}

go func() {

listener, err := net.ListenTCP("tcp", &adr)
if err != nil {
fmt.Println("服务器启动失败!")
exit <- true
return
}

for {
cdata := make([]byte, 1024)
client, err := listener.AcceptTCP()
if err != nil {
fmt.Println(err.Error())
continue
}
fmt.Println(client.RemoteAddr().String())
c, err := client.Read(cdata)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(string(cdata[0:c]))
client.Write([]byte("你好客户端!" + string(cdata[0:c])))
client.Close()

}

}()
<-exit
}

 

你可能感兴趣的:(socket)