新人求助!golang 怎么实现服务器被外网访问

desikee · · 203 次点击 · 开始浏览    置顶
我按照gopl上写了一个聊天服务器程序,想运行在阿里云服务器上,阿里云服务器能跑nginx,设置应该没问题 代码如下 ``` package main import( "fmt" "net" "log" "bufio" ) type client chan<- string var( entering = make(chan client) leave = make(chan client) messages = make(chan string) ) func main(){ listenner, err := net.Listen("tcp", "120.78.169.107:8000") if err != nil{ log.Fatal(err) } go broadcaster() for { conn, err := listenner.Accept() if err != nil{ log.Print(err) continue } go handleConn(conn) } } func broadcaster(){ clients := make(map[client] bool) for{ select{ case msg := <-messages: for cli := range clients{ go func (cli client, msg string){ cli <- msg }(cli, msg) } case cli := <-entering: clients[cli] = true case cli := <-leave: delete(clients, cli) close(cli) } } } func handleConn(c net.Conn){ ch := make(chan string) go clientWrite(c, ch) who := c.RemoteAddr().String() ch <- "Please input your name:" name := bufio.NewScanner(c) name.Scan() who = name.Text() ch <- "You are " + who entering <- ch messages <- who + " has arrived" input := bufio.NewScanner(c) for input.Scan(){ messages <- who + ": " + input.Text() } messages <- who + " has left" leave <- ch c.Close() } func clientWrite(c net.Conn, ch <-chan string){ for msg := range ch{ fmt.Fprintf(c, "\t%s\n", msg) } } ```
203 次点击  
加入收藏 微博
4 回复  |  直到 2017-12-08 10:15:27
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传