Easy TCP client and server for GO implementation

Source: Internet
Author: User

Today's introduction to the Golang version of the Communication Foundation: TCP-based client and server implementations, reference books: The "the" to Go

When learning Java was also done communication, then is the socket programming, the server listens to a certain port, and then the client to connect, simple chat room realized. Later has become multi-threaded chat room, can do group chat what, later can pass the picture to pass music, add UI that together, cottage QQ is OK. Now I'm going to use Golang to implement a simple chat room, the client connects to the server, sends a message to the server, the server accepts the message, the client exits, the server can receive the exit information, and multiple clients connect to a server at the same time. The main idea is the same as Java, the server listens to a certain port, the client goes to connect, then sends the message to be OK. On the code.
Package Main

Server-side
Import (
"FMT"
"Log"
"NET"//packet supporting communication
)

Start server
Func StartServer () {
Connect host, port, TCP communication, listen to 7777 port
Listener, err: = Net. Listen ("TCP", "localhost:7777")
CheckError (ERR)
Fmt. PRINTLN ("Build success!")
for {
Waiting for Client access
Conn, err: = Listener. Accept ()
CheckError (ERR)
Open a Goroutines processing client messages, this is the feature of Golang, the implementation of the concurrency is just go a bit better
Go Doserverstuff (conn)
}
}

Handling Client Messages
Func Doserverstuff (Conn net. Conn) {
Nameinfo: = Make ([]byte, 512)//Generate a cache array
_, ERR: = conn. Read (Nameinfo)
CheckError (ERR)

    for {
        buf: = Make ([]byte, +)
         _, Err: = conn. Read (BUF)//reads messages sent by client
        flag: = CheckError (err)
         if flag = = 0 {
            break
       }
        FMT. Println (String (BUF))//Print out
   }
}

Check for errors
Func checkerror (err error) int {
If err! = Nil {
If Err. Error () = = "EOF" {
Fmt. Println ("User exited")
return 0
}
Log. Fatal ("An error!", err. Error ())
Return-1
}
Return 1
}
Func Main () {
Open service
StartServer ()
}

The above is the implementation of the server, specifically see the code comments
Package Main

Client
Import (
"Bufio"
"FMT"
"Log"
"NET"
"OS"
"Strings"
)

Connecting to a server
Func ConnectServer () {
Connected
Conn, Err: = Net. Dial ("TCP", "localhost:7777")
CheckError (ERR)
Fmt. PRINTLN ("Connection Successful! \ n ")
Input
Inputreader: = Bufio. Newreader (OS. Stdin)
Fmt. Println ("Who Are You?") ")
Name, _: = inputreader.readstring (' \ n ')
//
Trimname: = Strings. Trim (name, "\ r \ n")
Conn. Write ([]byte (trimname + "Access \ n"))
for {
Fmt. PRINTLN ("Let's Talk!" Press quit to exit ")
Read a line
Input, _: = inputreader.readstring (' \ n ')
Triminput: = Strings. Trim (input, "\ r \ n")
If quit quit,
if triminput = = "Quit" {
Fmt. Println ("Good-Bye")
Conn. Write ([]byte (Trimname + "exited"))
Return
}
Write it up.
_, Err = conn. Write ([]byte (trimname + "says" + triminput))
}
}

Check for errors
Func checkerror (err error) {
If err! = Nil {
Log. Fatal ("An error!", err. Error ())
}
}

Main function
Func Main () {
Connection Servser
ConnectServer ()
}

The above is the client code, the specific view of the comments

When running, go run server and client respectively, you can see this can be connected successfully.
The server is open only, the client can open any one, and there is no interference between each other.

OK, a simple multi-threaded chat room is implemented. Later can add more functions, but is to deal with the input and output, the focus has already been.

--------------------------------------------------------------------------------

Welcome to make suggestions!

Easy TCP client and server for GO implementation

Related Article

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.