Created
October 17, 2014 16:45
-
-
Save memememomo/3f5947aea8fa3f09c250 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"strconv" | |
) | |
// ポート番号 | |
const PORT = 3540 | |
func main() { | |
// Listenする | |
server, err := net.Listen("tcp", ":"+strconv.Itoa(PORT)) | |
if err != nil { | |
panic("couldn't start listening") | |
} | |
// 接続待ち | |
conns := clientConns(server) | |
for { | |
// 接続があった場合、チャンネルにデータが送られてくる | |
go handleConn(<-conns) | |
} | |
} | |
func clientConns(listener net.Listener) chan net.Conn { | |
// チャンネルを作成 | |
ch := make(chan net.Conn) | |
// Listenする関数を定義して、goroutineで実行する | |
i := 0 | |
go func() { | |
for { | |
// 受信する | |
client, err := listener.Accept() | |
if err != nil { | |
fmt.Printf("couldn't accept") | |
continue | |
} | |
i++ | |
fmt.Printf("%d: %v <-> %v\n", i, client.LocalAddr(), client.RemoteAddr()) | |
// 受信したものをチャンネルに送信する | |
ch <- client | |
} | |
}() | |
// チャンネルを返す | |
return ch | |
} | |
func handleConn(client net.Conn) { | |
// 読み込み | |
b := bufio.NewReader(client) | |
for { | |
// 文字列を読み込む | |
line, err := b.ReadBytes('\n') | |
// 読み込み修了 | |
if err != nil { | |
break | |
} | |
// 送信 | |
client.Write(line) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment