Go language basic TCP programming client and server

Operation steps of TCP programming:
server and client server : step1: specify your own ip (local ip) and port net.ResolveTCPAddr("tcp4",string)-->TCPAddr   step2: get the listener, listen to the port listener, err:=net.ListenTCP(tcpAddr)   step3: Receive the connection request from the client listener.Accept()-->conn step4: Data interaction conn.Read() or conn.Write() Read or write step5: Close the resource










conn.Close() 

package main

import (
   "net"
   "fmt"
)

func main () {
    //TCP-based server
    //step1: Determine the address of the machine: ip:port--->TCPAddr Violent
    service := ":54321" // string
    tcpAddr , err:=net.ResolveTCPAddr( " tcp4" , service)
   fmt.Println(tcpAddr,err)
   fmt.Printf( "%T\n" , tcpAddr) //*net.TCPAddr
    //step2: listen to the port
 listener , err:=net.ListenTCP( "tcp" , tcpAddr)
   
   fmt.Println(listener,err)
   fmt.Printf( "%T\n" , listener) //*net.TCPListener
    //step3: Receive the connection request from the client
    fmt.Println( "The server program is ready, waiting for the connection from the client..." )
   conn , err:=listener.Accept() //blocking
    fmt.Println(conn , err) //&{{0xc042076000}} <nil>
    fmt.Printf( "%T\n" , conn) //*net .TCPConn
    fmt.Println( "A client has connected.." , conn.RemoteAddr())

   //step4: data interaction
    bs := make ([] byte , 512 )
   n,err:=conn.Read(bs)
   fmt.Println(n,err)
   fmt.Println( "Client said:" , string (bs[:n]))
   conn.Write([] byte ( "I am the server" ))

   //step5: Close the resource
    conn.Close()
}

Client:
step1: specify the ip and port of the server
step2: apply for connection to the specified server
net.DialTCP("tcp",tcpAddr)-->tcpConn
step3: data interaction
tcpConn.Read () or tcpConn.Write()
step4: close the resource

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()//
}
/*
客户端是你自己
客户端读取键盘输入,传递给服务端一句话
服务端是你同桌
服务端读取键盘输入,传递给客户端一句话
 */




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325943127&siteId=291194637