我按照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)
}
}
```
1、首先阿里云,。你要确定安全组问题,学会排查问题
2、可以不监听所有IP,具体看你服务器,如果是VPC环境下的,只监听内网IP就可以了,如果是服务器在非VPC环境下,在机器上你是可以看到公有网络IP的,可以监听公网IP
#4
更多评论