Simple TCP programming in the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Pre-preparation

    • Need a import "net" Package
    • IPType, one of the important methods is IP.ParseIP(ipaddr string) to determine whether it is a legitimate IP address

TCP Client

  • func (c *TCPConn) Write(b []byte) (n int, err os.Error)Used to send data, return the length of data sent or return an error, is TCPConn the method
  • func (c *TCPConn) Read(b []byte) (n int, err os.Error)The method used to receive data, return the length of the receive, or return an error. TCPConn
  • TCPAddrType, save address information for TCP, including address and port

      type TCPAddr struct {      IP IP      Port int  }
  • func ResolveTCPAddr(net, addr string) (*TCPAddr, os.Error)Get one TCPAddr , the parameters are all string types, net is a, const string including, tcp4 tcp6 tcp generally used tcp , compatible with V4 and V6, addr representing IP addresses, including port numbers, such as www.google.com:80
  • func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error)Used to connect (connect) to a remote server, net means the protocol tcp , tcp4 or tcp6 , a laddr native address, typically nil , represents a raddr remote address, here laddr and raddr all TCPAddrtype, which is typically the return value of the previous function.
  • As a TCP client, the basic operation flow is as follows:

      service="www.google.com:80"  tcpAddr, err := net.ResolveTCPAddr("tcp4", service)  conn, err := net.DialTCP("tcp", nil, tcpAddr)  _, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))  _, err = conn.Read(b) / result, err := ioutil.ReadAll(conn)

TCP Server

    • func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.Error)Used to listen to a port, to net indicate a protocol type, to laddr represent a native address, to be a TCPAddr type, note that the laddr here include a port, return a *TCPListener type or error
    • func (l *TCPListener) Accept() (c Conn, err os.Error)Used to return a new connection for subsequent operations, this is TCPListener the method that is generally TCPListener returned from the previous function.
    • The basic operating procedures for the server are:

        service:=":9090"  tcpAddr, err := net.ResolveTCPAddr("tcp4", service)  l,err := net.ListenTCP("tcp",tcpAddr)  conn,err := l.Accept()  go Handler(conn) //此处使用go关键字新建线程处理连接,实现并发

An example

Demand

Implement a public chat server.

    • server receives client-side information
    • Sends the client's information to all clients after it has been received
    • Client uses /quit exit Chat
    • Use only one set of code to start a server or client with command-line arguments

implementation:
Package Mainimport ("FMT" "OS" "NET")////////////////////////////////////////////////////////////error checking///////////// Func checkerror (Err Error,info string) (res bool) {if (err! = nil) {FMT. Println (info+ "" + Err. Error ()) return False}return true}////////////////////////////////////////////////////////////server-side receive data thread//parameter:// Data connection conn//communication channel Messages//////////////////////////////////////////////////////////func Handler (Conn net. Conn,messages Chan string) {fmt. PRINTLN ("Connection is connected from ...", Conn. Remoteaddr (). String ()) BUF: = make ([]byte,1024) for{lenght, err: = conn. Read (BUF) if (CheckError (Err, "Connection") ==false) {Conn. Close () break}if lenght > 0{buf[lenght]=0}//fmt. Println ("rec[", Conn. Remoteaddr (). String (), "] Say:", String (buf[0:lenght)) Recivestr: =string (Buf[0:lenght]) messages <-recivestr}}/////////////// The server sends the data thread////parameter//connection dictionary conns//data channel messages//////////////////////// //////////////////////Func Echohandler (Conns *map[string]net. Conn,messages Chan string) {for{msg:= <-messagesfmt. PRINTLN (msg) for Key,value: = Range *conns {fmt. PRINTLN ("Connection is connected from ...", key) _,err: =value. Write ([]byte (msg)) if (err! = nil) {FMT. Println (Err. Error ()) Delete (*conns,key)}}}}////////////////////////////////////////////////////////////start server//Parameter//Port port/// Func startserver (Port string) {service:= ":" +port//strconv. Itoa (port); Tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", Service) CheckError (err, "resolvetcpaddr") L,err: = Net. LISTENTCP ("TCP", TCPADDR) checkerror (err, "listentcp") Conns:=make (map[string]net. CONN) Messages: = Make (chan string,10)//Start server broadcast thread go Echohandler (&conns,messages) for {fmt. Println ("Listening ...") Conn,err: = L.accept () checkerror (err, "Accept") fmt. Println ("Accepting ...") conns[conn. Remoteaddr (). String ()]=conn//start a new thread go Handler (conn,messages)}}//////////////////////////////////////////////////////////// CustomerEnd send thread//parameter//Send connection Conn//////////////////////////////////////////////////////////func chatsend (conn net. Conn) {var input stringusername: = Conn. Localaddr (). String () for {fmt. SCANLN (&input) if input = = "/quit" {fmt. Println ("Byebye..") Conn. Close () OS. Exit (0);} Lens,err: =conn. Write ([]byte (username + "Say:::" + input)] FMT. PRINTLN (Lens) if (err! = nil) {FMT. Println (Err. Error ()) Conn. Close () break}}}////////////////////////////////////////////////////////////client startup function//parameter//remote IP address and port tcpaddr////// Func startclient (tcpaddr string) {tcpaddr, err: = Net. RESOLVETCPADDR ("TCP4", tcpaddr) checkerror (err, "RESOLVETCPADDR") conn, err: = Net. DIALTCP ("TCP", Nil, tcpaddr) checkerror (err, "dialtcp")//Start client send thread go chatsend (conn)//Start client rotation buf: = make ([]byte,1024) For{lenght, ERR: = conn. Read (BUF) if (CheckError (Err, "Connection") ==false) {Conn. Close () fmt. Println ("Server is dead ... Byebye ") os. Exit (0)}fmt. Println (String (buf[0:lenght))}}////////////////////////////////////////////Main program////parameter description://Start server side: Chat Server [port]eg:chat server 9090//start client: chat client [Server Ip Addr]:[ser Ver Port] Eg:chat client 192.168.0.74:9090//////////////////////////////////////////////////////////func main () {if Len (OS. Args)!=3 {fmt. Println ("Wrong pare") os. Exit (0)}if OS. args[1]== "Server" && len (OS. Args) ==3 {startserver (OS. ARGS[2])}if OS. args[1]== "Client" && len (OS. Args) ==3 {startclient (OS. ARGS[2])}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.