我按照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)
}
}
```
更多评论
安全组是要设置,主要是设置哪些端口开启自定义TCP,我已经开启了8000/8888端口。
代码部分net.Listen函数实参错了,应改为net.Listen("tcp", ":8000"),即监听所有IP
#3