golang - golang 네트워크 서버 작성.. tcp 다중 소켓 예제, tcp multi socket example
이 름 : 바다아이
|
조회수 : 11180
짧은 주소 : https://www.bada-ie.com/su/?901591832863
퍼왔는데 부족한 부분이 있어서 조금 수정 했습니다.
tcp 소켓 흐름 보시는데 도움이 될 겁니다.. 그리고...
http://localhost:6060/debug/pprof/
여기 접속하시면 프로파일링 됩니다. go 루틴이 정상적으로 종료되는지 확인도 해 보세요..서버package main
import (
"bufio""fmt""log""net""net/http"
_ "net/http/pprof""strings"
)
var (
CONNECT map[net.Conn]int
)
funcmain() {
CONNECT = make(map[net.Conn]int)
fmt.Println("Launching server...")
// listen on all interfaces
ln, _ := net.Listen("tcp", ":8081")
defer ln.Close()
gofunc() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// run loop forever (or until ctrl-c)for {
// accept connection on port
conn, _ := ln.Accept()
CONNECT[conn] = 1gofunc() {
for {
// will listen for message to process ending in newline (\n)
message, err := bufio.NewReader(conn).ReadString('\n')
// 접속이 끊어졌을 때..... 소켓 삭제 후 고루틴을 끝낸다.if err != nil {
delete(CONNECT, conn)
fmt.Println("\n이놈 접속 끊어짐 : \n")
fmt.Println(conn)
fmt.Println("\n")
break
}
// output message received
fmt.Print(conn)
fmt.Print(" -- Message Received: ", string(message))
// sample process for string received
newmessage := strings.ToUpper(message)
// send new string back to client
conn.Write([]byte(newmessage + "\n"))
}
}()
fmt.Println("\n현재 접속자 : \n")
for key, _ := range CONNECT {
fmt.Println(key)
}
fmt.Println("\n")
}
}
클라이언트package main
import (
"bufio""fmt""net""os"
)
funcmain() {
// connect to this socket
conn, _ := net.Dial("tcp", "127.0.0.1:8081")
for {
// read in input from stdin
reader := bufio.NewReader(os.Stdin)
fmt.Print("Text to send: ")
text, _ := reader.ReadString('\n')
// send to socket
fmt.Fprintf(conn, text+"\n")
// listen for reply
message, _ := bufio.NewReader(conn).ReadString('\n')
fmt.Print("Message from server: " + message)
}
}
출처 : https://systembash.com/a-simple-go-tcp-server-and-tcp-client/
|
|
번 호
카테고리
제 목
이름
조회수
Copyright ⓒ 2001.12. bada-ie.com. All rights reserved.
이 사이트는 리눅스에서 firefox 기준으로 작성되었습니다. 기타 브라우저에서는 다르게 보일 수 있습니다.
[ Ubuntu + GoLang + PostgreSQL + Mariadb ]
서버위치 : 오라클 클라우드 춘천 실행시간 : 0.33389 초 to webmaster... gogo sea. gogo sea.