Friday, 13 November 2020

golang 16 socket.io

client 1 ping server first, then broadcast
client 1 received broadcast from client 2


//cmd - server
 
C:\Users\bob\golang6>go run main.go
2020/11/14 15:02:03 Serving at localhost:8000...
connected: 1
connected: 2
notice: client 1 ping server
notice: client 2 ping server
broadcast: hello from client 1
broadcast: hi from client 2
1 closed client namespace disconnect
2 closed client namespace disconnect
//main.go
package main

import (
"fmt"
"log"
"net/http"

socketio "github.com/googollee/go-socket.io"
)

func main() {
server := socketio.NewServer(nil)

server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
s.Join("room1")
fmt.Println("connected:", s.ID())
return nil
})

server.OnEvent("/", "ping", func(s socketio.Conn, msg string) {
fmt.Println("notice:", msg)
s.Emit("pingReply", "ping: "+msg)
})

//broadcast
server.OnEvent("/", "broadcast", func(s socketio.Conn, msg string) {
fmt.Println("broadcast:", msg)
server.BroadcastToRoom("/", "room1", "serverBroadcast", "broadcast: "+msg)
})

server.OnEvent("/", "bye", func(s socketio.Conn) string {
last := s.Context().(string)
s.Emit("bye", last)
s.Close()
return last
})

server.OnError("/", func(s socketio.Conn, e error) {
fmt.Println("meet error:", e)
})

server.OnDisconnect("/", func(s socketio.Conn, reason string) {
fmt.Println(s.ID(), "closed", reason)
})

go server.Serve()
defer server.Close()

http.Handle("/socket.io/", server)
http.Handle("/", http.FileServer(http.Dir("./static")))
log.Println("Serving at localhost:8000...")
log.Fatal(http.ListenAndServe(":8000", nil))
}

----------------------
//index.html
<!doctype html>
<html>

<head>
    <title>Socket.IO chat</title>
    <link rel="stylesheet" type="text/css" href="/static/index.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font: 30px Helvetica, Arial;
        }

        #form1 {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 0;
            width: 100%;
        }

        #form2 {
            background: #000;
            padding: 3px;
            position: fixed;
            bottom: 60px;
            width: 100%;
        }

        form input {
            border: 0;
            padding: 10px;
            width: 79%;
            margin-right: .5%;
            font-size: 30px;
        }

        form button {
            width: 20%;
            background: rgb(130, 224, 255);
            border: none;
            padding: 10px;
            font-size: 30px;
        }

        #messages {
            list-style-type: none;
            margin: 0;
            padding: 0;
        }

        #messages li {
            padding: 5px 10px;
        }

        #messages li:nth-child(odd) {
            background: #eee;
        }
    </style>
</head>

<body>
    <ul id="messages"></ul>
    <form id="form1" action="">
        <input id="m" autocomplete="off" /><button>Ping Server</button>
    </form>
    <form id="form2" action="">
        <input id="m2" autocomplete="off" /><button>Broadcast</button>
    </form>
    <script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script>
        var socket = io();

        socket.on('pingReply', function (msg) {
            $('#messages').append($('<li>').text(msg));
        });

        socket.on('serverBroadcast', function (msg) {
            $('#messages').append($('<li>').text(msg));
        });

        $('#form1').submit(function () {

            socket.emit('ping', $('#m').val());
            $('#m').val('');
            return false;
        });

        $('#form2').submit(function () {

            socket.emit('broadcast', $('#m2').val());
            $('#m2').val('');
            return false;
        });
    </script>
</body>

</html>

reference:

Thursday, 12 November 2020

golang 15 tcp client & server

 //cmd - client
C:\Users\bob\golang5>go run main.go
hi from server~

C:\Users\bob\golang5>go run main.go
hi from server~

C:\Users\bob\golang5>go run main.go
hi from server~

C:\Users\bob\golang5>go run main.go
hi from server~

//cmd - server
C:\Users\bob\golang4>go run main.go
hello from client~0
hello from client~1
hello from client~2
hello from client~3

//client main.go
package main

import (
"fmt"
"io/ioutil"
"net"
)

func main() {
conn, err := net.Dial("tcp", "192.168.0.18:9000")
if err != nil {
panic(err)
}
defer conn.Close()

_, err = conn.Write([]byte("hello from client~"))
if err != nil {
panic(err)
}

bs, _ := ioutil.ReadAll(conn)
message := string(bs)
fmt.Println(message)

if string(message[len(message)-1]) == "~" {
conn.Close()
}
}

------------------------
//server main.go
package main

import (
"fmt"
"net"
"strconv"
)

func main() {
ln, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
defer ln.Close()

for i := 0; ; i++ {
conn, err := ln.Accept()
if err != nil {
panic(err)
}

for {
bs := make([]byte, 1024)
n, err := conn.Read(bs)
if err != nil {
break
}

if string(bs[n-1]) == "~" {
_, err = conn.Write([]byte("hi from server~"))
if err != nil {
panic(err)
break
}
fmt.Println(string(bs[:n]) + strconv.Itoa(i))

conn.Close()
break
}

//_, err = conn.Write(bs[:n])
_, err = conn.Write([]byte("_"))
if err != nil {
break
}

fmt.Print(string(bs[:n]))
}

conn.Close()
}
}

reference:

Wednesday, 11 November 2020

golang 14 TCP Server

//cmd -client1
telnet 192.168.0.18 9000
  _l_i_e_n_t_1_
_

//cmd -client2
//client2 connects to server after client 1 connected, can't communicate to server first. After client 1 leaves, communation starts to work
          _c_l_i_e_n_t_2_ _s_t_a_r_t_ _t_o_ _t_y_p_e_

//cmd -server
C:\Users\bob\golang4>go run main.go
client1
can't typeclient2 start to type

----------------------------
//main.go - server
package main

import (
"fmt"
"net"
)

func main() {
ln, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
defer ln.Close()

for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}

for {
bs := make([]byte, 1024)
n, err := conn.Read(bs)
if err != nil {
break
}

//_, err = conn.Write(bs[:n])
_, err = conn.Write([]byte("_"))
if err != nil {
break
}

fmt.Print(string(bs[:n]))
}

conn.Close()
}
}

Monday, 9 November 2020

go web app 19 deploy to heroku


find GOPATH 
>go env GOPATH
C:\Users\bob\go

copy project directory to GOPATH/src
reinstall dependencies - go get ...

create go.mod
>go mod init example.com/election
go: creating new go.mod: module example.com/election

create go.sum
>go test
go: finding module for package github.com/gorilla/mux
go: finding module for package golang.org/x/crypto/bcrypt
...

create vendor folder
>govendor init

populate vendor folder
>go mod vendor

change port on main.go 
port := os.Getenv("PORT")
http.ListenAndServe(":"+port, nil)

create Procfile in project root directory (GOPATH/src)
web: bin/projectName

create new app on heroku
>git init
>heroku git:remote -a chuanshuoge-election
>git add .
>git commit -am "make it better"
>git push heroku master
remote:        https://chuanshuoge-election.herokuapp.com/ deployed to Heroku

free heroku dyno
>heroku ps:scale web=1

open app on heroku
go app is deployed on heroku
reference:

Sunday, 8 November 2020

Biden's Victory Speech

wechat privacy

 How do you check if someone is online on WeChat?

You ask the person if he / she is online.
That is the ONLY way.

How do I get the WeChat ID of a person?

There are 3 ways to get the WeChat ID of a person:

If the person is in your list of contacts, you can check his / her profile and see if he / she has set open the WeChat ID.
You can ask the person to show you or take a screenshot of their profile
Use his / her phone number and get WeChat to recommend his / her account to you.
Potential issues:

If your friend has disabled the option to be found by WeChat ID, then you can only do ONE thing: ASK him or her.

This happens even if you are friends on WeChat.

Blocking

The chief problem with WeChat is that you cannot block someone who is not already in your contacts list. This is a total make or break for this app which makes it very unappealing.
reference:

Saturday, 7 November 2020

go web app deploy reference

 
reference:

auto open web page after web server starts

go run ./

generate go.mod

C:\Users\bob\golang1>go mod init example.com/golang1
go: creating new go.mod: module example.com/golang1

C:\Users\bob\golang1>go test
go: finding module for package github.com/gorilla/mux
go: finding module for package github.com/gorilla/sessions
go: finding module for package go.mongodb.org/mongo-driver/mongo
go: finding module for package go.mongodb.org/mongo-driver/mongo/options
go: finding module for package go.mongodb.org/mongo-driver/bson
go: finding module for package golang.org/x/crypto/bcrypt
go: finding module for package go.mongodb.org/mongo-driver/bson/primitive
go: downloading go.mongodb.org/mongo-driver v1.4.3
go: downloading github.com/gorilla/sessions v1.2.1
go: downloading github.com/gorilla/mux v1.8.0
go: downloading golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
go: found github.com/gorilla/mux in github.com/gorilla/mux v1.8.0
go: found github.com/gorilla/sessions in github.com/gorilla/sessions v1.2.1
go: found go.mongodb.org/mongo-driver/bson in go.mongodb.org/mongo-driver v1.4.3
go: found go.mongodb.org/mongo-driver/bson/primitive in go.mongodb.org/mongo-driver v1.4.3
go: found go.mongodb.org/mongo-driver/mongo in go.mongodb.org/mongo-driver v1.4.3
go: found go.mongodb.org/mongo-driver/mongo/options in go.mongodb.org/mongo-driver v1.4.3
go: found golang.org/x/crypto/bcrypt in golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897
?       example.com/golang1     [no test files]

GOPATH  - project files has to be in GOPATH for deploy
>go env GOPATH
C:\Users\bob\go

govendor
govendor init
govendor add packageName
go mod vendor

go internal package - disable go internal check
create internal folder and move project files inside 
C:\Users\bob\go\src\internal\election

heroku - “no web processes running”

C:\Users\bob\go\src\heroku\election>git push heroku master
Enumerating objects: 666, done.
Counting objects: 100% (666/666), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (622/622), done.
Writing objects: 100% (666/666), 1.13 MiB | 590.00 KiB/s, done.
Total 666 (delta 69), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Go app detected
remote: -----> Fetching jq... done
remote: -----> Fetching stdlib.sh.v8... done
remote: ----->
remote:        Detected go modules via go.mod
remote: ----->
remote:        Detected Module Name: example.com/election
remote: ----->
remote:  !!    The go.mod file for this project does not specify a Go version
remote:  !!
remote:  !!    Defaulting to go1.12.17
remote:  !!
remote:  !!    For more details see: https://devcenter.heroku.com/articles/go-apps-with-modules#build-configuration
remote:  !!
remote: -----> New Go Version, clearing old cache
remote: -----> Installing go1.12.17
remote: -----> Fetching go1.12.17.linux-amd64.tar.gz... done
remote: -----> Determining packages to install
remote:
remote:        Detected the following main packages to install:
remote:                 example.com/election
remote:                 example.com/election/simulator
remote:
remote: -----> Running: go install -v -tags heroku -mod=vendor example.com/election example.com/election/simulator
remote: go.mongodb.org/mongo-driver/bson/bsonoptions
remote: github.com/gorilla/securecookie
remote: github.com/gorilla/mux
remote: github.com/gorilla/sessions
remote: go.mongodb.org/mongo-driver/bson/bsontype
remote: go.mongodb.org/mongo-driver/bson/primitive
remote: github.com/go-stack/stack
remote: github.com/pkg/errors
remote: go.mongodb.org/mongo-driver/x/bsonx/bsoncore
remote: go.mongodb.org/mongo-driver/tag
remote: go.mongodb.org/mongo-driver/mongo/readpref
remote: github.com/golang/snappy
remote: github.com/klauspost/compress/fse
remote: github.com/klauspost/compress/huff0
remote: go.mongodb.org/mongo-driver/bson/bsonrw
remote: go.mongodb.org/mongo-driver/mongo/readconcern
remote: github.com/klauspost/compress/snappy
remote: github.com/klauspost/compress/zstd/internal/xxhash
remote: github.com/klauspost/compress/zstd
remote: go.mongodb.org/mongo-driver/bson/bsoncodec
remote: go.mongodb.org/mongo-driver/x/mongo/driver/address
remote: go.mongodb.org/mongo-driver/x/mongo/driver/description
remote: go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt/options
remote: go.mongodb.org/mongo-driver/x/mongo/driver/mongocrypt
remote: go.mongodb.org/mongo-driver/x/mongo/driver/uuid
remote: go.mongodb.org/mongo-driver/x/mongo/driver/wiremessage
remote: go.mongodb.org/mongo-driver/internal
remote: go.mongodb.org/mongo-driver/x/mongo/driver/dns
remote: github.com/aws/aws-sdk-go/aws/awserr
remote: github.com/aws/aws-sdk-go/internal/ini
remote: go.mongodb.org/mongo-driver/bson
remote: github.com/aws/aws-sdk-go/internal/shareddefaults
remote: github.com/aws/aws-sdk-go/internal/sync/singleflight
remote: go.mongodb.org/mongo-driver/event
remote: go.mongodb.org/mongo-driver/mongo/writeconcern
remote: go.mongodb.org/mongo-driver/x/bsonx
remote: go.mongodb.org/mongo-driver/x/mongo/driver/session
remote: go.mongodb.org/mongo-driver/x/mongo/driver
remote: go.mongodb.org/mongo-driver/x/mongo/driver/connstring
remote: github.com/aws/aws-sdk-go/aws/credentials
remote: github.com/aws/aws-sdk-go/aws/endpoints
remote: go.mongodb.org/mongo-driver/mongo/options
remote: github.com/aws/aws-sdk-go/internal/sdkio
remote: github.com/jmespath/go-jmespath
remote: github.com/aws/aws-sdk-go/aws/awsutil
remote: github.com/aws/aws-sdk-go/aws/client/metadata
remote: github.com/aws/aws-sdk-go/internal/strings
remote: github.com/aws/aws-sdk-go/internal/sdkmath
remote: golang.org/x/text/transform
remote: golang.org/x/text/unicode/norm
remote: github.com/xdg/stringprep
remote: github.com/aws/aws-sdk-go/aws
remote: github.com/aws/aws-sdk-go/aws/request
remote: github.com/aws/aws-sdk-go/private/protocol
remote: github.com/aws/aws-sdk-go/private/protocol/rest
remote: github.com/aws/aws-sdk-go/aws/signer/v4
remote: golang.org/x/crypto/pbkdf2
remote: go.mongodb.org/mongo-driver/version
remote: go.mongodb.org/mongo-driver/x/mongo/driver/operation
remote: github.com/xdg/scram
remote: golang.org/x/crypto/ocsp
remote: golang.org/x/sync/errgroup
remote: go.mongodb.org/mongo-driver/x/mongo/driver/ocsp
remote: golang.org/x/sync/semaphore
remote: golang.org/x/crypto/blowfish
remote: golang.org/x/crypto/bcrypt
remote: go.mongodb.org/mongo-driver/x/mongo/driver/auth
remote: go.mongodb.org/mongo-driver/x/mongo/driver/topology
remote: go.mongodb.org/mongo-driver/mongo
remote: example.com/election
remote: example.com/election/simulator
remote:
remote:        Installed the following binaries:
remote:                 ./bin/election
remote:                 ./bin/simulator
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing...
remote:        Done: 16.6M
remote: -----> Launching...
remote:        Released v3
remote:        https://chuanshuoge-election.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/chuanshuoge-election.git
 * [new branch]      master -> master
heroku ps:scale web=1