Go/네트워크 프로그래밍/Tcp-Ip-Socket

1707 단어 GoLang
# 서버
package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {
	// 
	lisener,err := net.Listen("tcp","127.0.0.1:8888")
	defer lisener.Close()
	if err != nil{
		fmt.Println(err)
		return
	}

	for{
		// 
		conn,err := lisener.Accept()	//blocked
		if err != nil{
			fmt.Println(err)
			conn.Close()
			continue
		}

		// 
		go func(conn net.Conn){
			defer conn.Close()

			cli_addr := conn.RemoteAddr().String()
			fmt.Println("cli_addr: ",cli_addr)

			for{
				//read
				buf := make([]byte,1024)
				n,err := conn.Read(buf)
				if err != nil{
					fmt.Println(err)
					return
				}
				fmt.Println(" : ",string(buf[:n]), " : ", n)

				if string(buf[:n]) == "exit"{
					fmt.Println(" , ")
					return
				}

				//write
				buf = []byte(strings.ToUpper(string(buf[:n])))
				_,err = conn.Write(buf[:n])
				if err != nil {
					fmt.Println(err)
					return
				}
			}
		}(conn)
	}
}

# 클라이언트
package main

import (
	"fmt"
	"net"
)

func main() {
	// 
	conn,err := net.Dial("tcp","127.0.0.1:8888")
	defer conn.Close()
	if err != nil{
		fmt.Println(err)
		return
	}

	go func(){
		var strbuf string
		for{
			fmt.Print(" : ")
			fmt.Scanf("%s",&strbuf)
			if err != nil{
				fmt.Println(err)
				break
			}

			//write
			_,err = conn.Write([]byte(strbuf))	//\r
if err != nil{ fmt.Println(err) break } } }() //read buffer := make([]byte,1024) for{ n,err := conn.Read(buffer) if err != nil{ fmt.Println(err) return } fmt.Println(" : ",string(buffer[:n])) } }

좋은 웹페이지 즐겨찾기