CMU15-440 project-0:用Go实现一个广播回显的Server

最近在学习分布式系统,特定跟上了CMU15-440这门课。
写完了Project 0
Project 0 : 是让写一个能够回显的Echo Server
要求是每一个Client发送给Server消息,用\n来进行分割,并将收到的信息都返回给所有的用户:
下面是具体的实验要求(直接上英文,为了方便):
Your multi-client echo server must have the following characteristics:

  1. The server must manage and interact with its clients concurrently using goroutines and channels. Multiple clients should be able to connect/disconnect to the server simultaneously.

  2. The server should assume that all messages are line-oriented, separated by newline (\n) characters. When the server reads a newline-terminated message from a client, it must respond by writing that exact message (up to and including the newline character) to all connected clients, including the client that sent the message.

  3. The server must be responsive to slow-reading clients. To better understand what this means, consider a scenario in which a client does not call Read for an extended period of time. If during this time the server continues to write messages to the client’s TCP connection, eventually the TCP connection’s output buffer will reach maximum capacity and subsequent calls to Write made by the server will block.

To handle these cases, your server should keep a queue of at most 100 outgoing messages to be written to the client at a later time. Messages sent to a slow-reading client whose outgoing message buffer has reached the maximum capacity of 100 should simply be dropped. If the slow-reading client starts reading again later on, the server should make sure to write any buffered messages in its queue back to the client. (Hint: use a buffered channel to implement this property).

这个实验的难度不大,重点是为了熟悉Go语言以及go和chan

需要注意的点:
一个启动了4个协程:

  1. Server端需要启动协程来处理client的请求。
  2. 启动一个广播协程,向所有存活的用户发送消息
  3. 读取client请求协程,读取Client所读取的所有信息(用空格来进行分割,一个空格一条信息)。
  4. 向client写协程,单独起一个协程,for循环来读取服务端发送的信息,并写向client。

这里,要注意熟悉Go语言的chan的阻塞特性,
利用chan来作为锁,即简单点表示就是

 <- chan

只有当chan管道收到消息的时候,才会继续运行,所以可以将chan作为阻塞锁来用。
通过发送消息来对协程进行唤醒。
同时,要熟悉select的chan选择特性,select本身也是阻塞的。

select {
   
   case <- chan:
}

具体的代码如下:

// Implementation of a MultiEchoServer. Students should write their code in this file.

package p0

import (
	"bufio"
	"net";
//	"time";
	"strconv";
	"fmt";
)


const (
	MaxQueue=100  //max buffer size
)


type clientinfo struct {
   
	conn net.Conn
	WriteBuffChan chan string
	live bool
}


type multiEchoServer struct {
   
	// TODO: implement this!
	// 结构体存储指针,不能存储整个结构体的空间
	client [
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值