|
| 1 | +// package main simulates a conversation between |
| 2 | +// a given set of websocket clients and a server. |
| 3 | +// |
| 4 | +// It spins up a web socket server. |
| 5 | +// On a client's connection it creates a SenderReceiver which handles JSON Stream |
| 6 | +// encoding and decoding using gojay's streaming API to abstract JSON communication |
| 7 | +// between server and client, only having to handle go values. |
| 8 | +// |
| 9 | +// To simulate a conversation: |
| 10 | +// - the server sends a welcome message to the client |
| 11 | +// - when the client receives the message, it sends a message back to the server |
| 12 | +// - when the server receives the ack message, it will send a message randomly to a client |
| 13 | +// - when the client receives the message, it sends a message back to the server... and so on. |
| 14 | +package main |
| 15 | + |
| 16 | +import ( |
| 17 | + "log" |
| 18 | + "strconv" |
| 19 | + |
| 20 | + "github.com/francoispqt/gojay/examples/websocket/client" |
| 21 | + "github.com/francoispqt/gojay/examples/websocket/comm" |
| 22 | + "github.com/francoispqt/gojay/examples/websocket/server" |
| 23 | +) |
| 24 | + |
| 25 | +func createServer(done chan error) { |
| 26 | + // create our server, with a done signal |
| 27 | + s := server.NewServer() |
| 28 | + // set our connection handler |
| 29 | + s.OnConnection(func(c *server.Client) { |
| 30 | + // send welcome message to initiate the conversation |
| 31 | + c.SendMessage(&comm.Message{ |
| 32 | + UserName: "server", |
| 33 | + Message: "Welcome !", |
| 34 | + }) |
| 35 | + // start handling messages |
| 36 | + c.OnMessage(func(m *comm.Message) { |
| 37 | + log.Print("message received from client: ", m) |
| 38 | + s.BroadCastRandom(c, m) |
| 39 | + }) |
| 40 | + }) |
| 41 | + go s.Listen(":8070", done) |
| 42 | +} |
| 43 | + |
| 44 | +func createClient(url, origin string, i int) { |
| 45 | + // create our client |
| 46 | + c := client.NewClient(i) |
| 47 | + // Dial connection to the WS server |
| 48 | + err := c.Dial(url, origin) |
| 49 | + if err != nil { |
| 50 | + panic(err) |
| 51 | + } |
| 52 | + str := strconv.Itoa(i) |
| 53 | + // Init client's sender and receiver |
| 54 | + // Set the OnMessage handler |
| 55 | + c.OnMessage(func(m *comm.Message) { |
| 56 | + log.Print("client "+str+" received from "+m.UserName+" message: ", m) |
| 57 | + c.SendMessage(&comm.Message{ |
| 58 | + UserName: str, |
| 59 | + Message: "Responding to: " + m.UserName + " | old message: " + m.Message, |
| 60 | + }) |
| 61 | + }) |
| 62 | +} |
| 63 | + |
| 64 | +// Our main function |
| 65 | +func main() { |
| 66 | + done := make(chan error) |
| 67 | + createServer(done) |
| 68 | + // add our clients connection |
| 69 | + for i := 0; i < 100; i++ { |
| 70 | + i := i |
| 71 | + go createClient("ws://localhost:8070/ws", "http://localhost/", i) |
| 72 | + } |
| 73 | + // handle server's termination |
| 74 | + log.Fatal(<-done) |
| 75 | +} |
0 commit comments