1. 程式人生 > >Go語言實現簡單伺服器和客戶端

Go語言實現簡單伺服器和客戶端

Go語言實現伺服器和客戶端比較簡單
伺服器:
listen
accept
recv

客戶端
dial
write

1.server.go

package main

import (
    "log"
    "net"
    "os"
)

func recvMessage(client net.Conn) error {
    var message []byte
    message = make([]byte, 1024)

    for {
        len, _ := client.Read(message)
        if len > 0
{ log.Println(message[0:len]) } } return nil } func main() { server, err := net.Listen("tcp", "localhost:9700") if err != nil { log.Fatal("start server failed!\n") os.Exit(1) } defer server.Close() log.Println("server is running...") for
{ client, err := server.Accept() if err != nil { log.Fatal("Accept error\n") continue } log.Println("the client is connectted...") go recvMessage(client) } }

2.client.go

package main

import (
    "log"
    "net"
    "os"
)

func
main() { client, err := net.Dial("tcp", "localhost:9700") if err != nil { log.Fatal("Client is dailing failed!") os.Exit(1) } client.Write([]byte("i am client")) client.Close() }