go语言基础 TCP编程 客户端和服务器

TCP编程的操作步骤:
服务器和客户端
服务端:
step1:指定自己的ip(本机ip)和端口
net.ResolveTCPAddr("tcp4",string)-->TCPAddr  
step2:获取监听器,监听端口
listener,err:=net.ListenTCP(tcpAddr)  
step3:接收客户端的连接请求
listener.Accept()-->conn
step4:数据交互
conn.Read()或者conn.Write() 读或者写
step5:关闭资源

conn.Close() 

package main

import (
   "net"
   "fmt"
)

func main()  {
   //基于TCP的服务器
   //step1:确定本机的地址:ip:port--->TCPAddr烈性
   service := ":54321" // string
   tcpAddr,err:=net.ResolveTCPAddr("tcp4",service)
   fmt.Println(tcpAddr,err)
   fmt.Printf("%T\n",tcpAddr) //*net.TCPAddr

   //step2:监听该端口
   listener,err:=net.ListenTCP("tcp", tcpAddr)
   fmt.Println(listener,err)
   fmt.Printf("%T\n",listener) //*net.TCPListener
   //step3:接收客户端的连接请求
   fmt.Println("服务器程序已经就绪,等待客户端的链接。。。")
   conn,err:=listener.Accept()//阻塞式
   fmt.Println(conn, err) //&{{0xc042076000}} <nil>
   fmt.Printf("%T\n", conn) //*net.TCPConn
   fmt.Println("已有客户端连入。。",conn.RemoteAddr())

   //step4:数据交互
   bs := make([] byte,512)
   n,err:=conn.Read(bs)
   fmt.Println(n,err)
   fmt.Println("客户端说:", string(bs[:n]))
   conn.Write([] byte("我是服务器"))

   //step5:关闭资源
   conn.Close()
}

客户端:
step1:指定服务器的ip和端口
step2:申请连接指定服务器
net.DialTCP("tcp",tcpAddr)-->tcpConn
step3:数据交互
tcpConn.Read()或者tcpConn.Write()
step4:关闭资源

tcp.Close()

package main

import (
   "net"
   "fmt"
)

func main()  {
   //TCP的客户端程序
   //step1:提供要连接的服务端的地址
   service:="10.0.154.238:54321" //是服务器的地址,不是自己的,自己的端口由系统自动分配
   tcpAddr,err:=net.ResolveTCPAddr("tcp4",service)
   fmt.Println(tcpAddr,err) //10.0.154.238:54321 nil
   // step2:申请连接服务器
   tcpConn, err:=net.DialTCP("tcp",nil,tcpAddr)
   fmt.Println(tcpConn,err) //&{{0xc042088000}} <nil>
   fmt.Printf("%T\n", tcpConn) //*net.TCPConn
   fmt.Println("客户端已经连接成功。。。")
   fmt.Println("服务器的地址:",tcpConn.RemoteAddr())
   //step3:数据交互
   n,err:=tcpConn.Write([] byte("hello"))//写出的字节的数量
   fmt.Println(n,err)
   fmt.Println("数据已经写出。。")

   bs := make([] byte,512)
   n,err=tcpConn.Read(bs)
   fmt.Println(string(bs[:n]))
   //step4.关闭资源,断开连接
   tcpConn.Close()//
}
/*
客户端是你自己
客户端读取键盘输入,传递给服务端一句话
服务端是你同桌
服务端读取键盘输入,传递给客户端一句话
 */




猜你喜欢

转载自blog.csdn.net/weixin_42100098/article/details/80149601