golang实现简单的socket
简单使用,直接上代码
服务端:
package main
import (
"fmt"
"net"
)
func main() {
// 创建服务器地址
addr, _ := net.ResolveTCPAddr("tcp4", "localhost:8089")
// 创建监听器
tcp, _ := net.ListenTCP("tcp4", addr)
fmt.Println("启动")
// 获取数据
// 关闭连接
for{
accept, _ := tcp.Accept()
go func(){
bytes := make([]byte, 1024)
n, _ := accept.Read(bytes)
fmt.Println("获取到的数据为:" ,string(bytes[:n]))
accept.Write(append([]byte("服务器返回来的消息:"), bytes[:n]...))
accept.Close()
}()
}
}
客户端:
package main
import (
"fmt"
"net"
)
func main() {
addr, _ := net.ResolveTCPAddr("tcp4", "localhost:8089")
conn, _ := net.DialTCP("tcp4", nil, addr)
conn.Write([]byte("客户端发送数据"))
b:=make([]byte,1024)
count, _ := conn.Read(b)
fmt.Println("server:", string(b[:count]))
conn.Close()
}
这个就是简单socket
下面是一个类似于微信聊天的服务,可以启动玩一玩
服务端
package main
import (
"fmt"
"net"
"strings"
)
type User struct {
UserName string
OtherUserName string
Msg string
ServerMsg string
}
var (
userMap = make(map[string]net.Conn)
user = new(User)
)
func main(){
// 创建地址
addr,_:=net.ResolveTCPAddr("tcp4","localhost:8899")
// 创建监听器
tcp, _ := net.ListenTCP("tcp4", addr)
for {
// 通过监听器创建连接对象
conn,_:=tcp.Accept()
go func() {
for{
// 读取数据
b:=make([]byte,1024)
// 获取连接
n, _ := conn.Read(b)
array := strings.Split(string(b[:n]), "-")
user.UserName = array[0]
user.OtherUserName = array[1]
user.Msg = array[2]
user.ServerMsg = array[3]
userMap[user.UserName] = conn
if v,ok:=userMap[user.OtherUserName];ok&&v!=nil{
n, err := v.Write([]byte (fmt.Sprintf("%s-%s-%s-%s", user.UserName,user.OtherUserName,user.Msg,user.ServerMsg)))
if n <= 0 || err != nil{
delete(userMap,user.OtherUserName)
// 关闭连接
conn.Close()
v.Close()
fmt.Println("if....")
break
}
fmt.Println("发送消息成功")
}else {
user.ServerMsg = "对方不在线"
conn.Write([]byte (fmt.Sprintf("%s-%s-%s-%s", user.UserName,user.OtherUserName,user.Msg,user.ServerMsg)))
}
}
}()
}
}
客户端:
package main
import (
"fmt"
"net"
"os"
"strings"
"sync"
)
type User struct {
UserName string
OtherUserName string
Msg string
ServerMsg string
}
var (
user = new(User)
wg sync.WaitGroup
)
func main() {
wg.Add(1)
fmt.Println("请输入账号")
fmt.Scanln(&user.UserName)
fmt.Println("请输入要给谁发送消息:")
fmt.Scanln(&user.OtherUserName)
addr, _ := net.ResolveTCPAddr("tcp4", "localhost:8899")
conn, _ := net.DialTCP("tcp4", nil, addr)
// sendMsg
go func() {
fmt.Println("请输入您要发送的消息: ")
for{
fmt.Scanln(&user.Msg)
if user.Msg == "exit" {
conn.Close()
wg.Done()
os.Exit(0)
}
conn.Write([]byte (fmt.Sprintf("%s-%s-%s-%s", user.UserName,user.OtherUserName,user.Msg,user.ServerMsg)))
}
}()
// 接受消息
go func() {
for{
b := make([]byte, 1024)
count, _ := conn.Read(b)
array := strings.Split(string(b[:count]),"-")
user2 := new(User)
user2.UserName = array[0]
user2.OtherUserName = array[1]
user2.Msg = array[2]
user2.ServerMsg = array[3]
if user2.ServerMsg != ""{
fmt.Println("\t\t服务器的消息:",user2.ServerMsg)
}else{
fmt.Println("\t\t",user2.UserName,":",user2.Msg)
}
}
}()
wg.Wait()
}