tcp连接
服务器端
package main
import (
"fmt"
"net"
"strings"
)
func HandleConnect( conn net.Conn) {
defer conn.Close()
addr:=conn.RemoteAddr()
fmt.Println(addr,"客户端成功连接")
buf:=make([]byte,4096)
for {
n,err:=conn.Read(buf)
if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]){
fmt.Println("客户端关闭连接")
return
}
if n ==0 {
fmt.Println("Client is close")
return
}
if err != nil {
fmt.Println("conn Read err",err)
return
}
fmt.Println("服务器读到客户端数据:",string(buf[:n]))
conn.Write([]byte(strings.ToUpper(string(buf[:n]))))
}
}
func main(){
listener,err:= net.Listen("tcp","127.0.0.1:9001")
if err != nil {
fmt.Println("net.listen is error")
return
}
defer listener.Close()
fmt.Println("服务器等待客户端连接...")
for {
conn,err:= listener.Accept()
if err != nil {
fmt.Println("accept is error")
return
}
go HandleConnect(conn)
}
}
客户端
package main
import (
"fmt"
"net"
"os"
)
func main(){
conn,err:=net.Dial("tcp","127.0.0.1:9001")
if err != nil {
fmt.Println("connect server is error")
return
}
defer conn.Close()
go func(){
str:=make([]byte,4096)
for {
n,err:=os.Stdin.Read(str)
if n ==0 {
fmt.Println("server is close")
return
}
if err != nil {
fmt.Println("os.Stdin is error")
continue
}
conn.Write(str[:n])
}
}()
//读取服务器
buf:=make([]byte,4096)
for {
n,err:=conn.Read(buf)
if n == 0 {
fmt.Println("服务端关闭连接了...")
return
}
if "exit\n" == string(buf[:n]) || "exit\r\n" == string(buf[:n]) {
fmt.Println("客户端关闭连接")
return
}
if err != nil {
fmt.Println("os.buf is error")
return
}
fmt.Println("客户端读到服务端数据:", string(buf[:n]))
}
}
使用案例【tcp发送文件】------------------------------------------------
服务端
package main
import (
"fmt"
"io"
"log"
"net"
"os"
)
func recvFile(conn net.Conn,fileName string){
f,err:=os.Create(fileName)
if err != nil {
log.Println("Create File is error")
return
}
defer f.Close()
buf:=make([]byte,4096)
for {
n,_:=conn.Read(buf)
if n==0 {
fmt.Println("finsh")
return
}
f.Write(buf[:n])
}
}
func main(){
listener,err:= net.Listen("tcp","127.0.0.1:8007")
if err != nil {
fmt.Println("net.Listen is error")
return
}
defer listener.Close()
conn,err:=listener.Accept()
//获取文件名字
bufName:=make([]byte,4096)
n,err:=conn.Read(bufName)
if err != nil {
if err == io.EOF {
fmt.Println("finish")
}
return
}
fileName:= string(bufName[:n])
recvFile(conn,fileName)
}
客户端
package main
import (
"fmt"
"io"
"log"
"net"
"os"
)
func readFile(conn net.Conn,path string){
fd,_:=os.Open(path)
buf:=make([]byte,4096)
for {
n,err:=fd.Read(buf)
if err == io.EOF {
fmt.Println("send file fiinish")
return
}
conn.Write(buf[:n])
}
defer fd.Close()
}
func main(){
lists:= os.Args
if len(lists) != 2 {
log.Println("params is errors")
return
}
path:= lists[1]
conn,err:=net.Dial("tcp","127.0.0.1:8007")
if err != nil {
fmt.Println("conn is erros")
return
}
defer conn.Close()
fileInfo,_:= os.Stat(path)
fileName := fileInfo.Name()
fmt.Println(fileName)
conn.Write([]byte(fileName))//发送文件名字
readFile(conn,path)
}