initial working version

This commit is contained in:
Timo Volkmann 2020-11-07 12:18:45 +01:00
commit c511491229

232
server.go Normal file
View File

@ -0,0 +1,232 @@
package main
import (
"fmt"
"github.com/gorilla/websocket"
"github.com/tidwall/pretty"
"html/template"
"log"
"net"
"net/http"
"os"
)
const (
//CONN_HOST = "localhost"
CONN_PORT = ":3010"
CONN_TYPE = "tcp"
)
var upgrader = websocket.Upgrader{} // use default options
func echo(channel <-chan string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
//mt, message, err := c.ReadMessage()
//if err != nil {
// log.Println("read:", err)
// break
//}
//log.Printf("recv: %s", message)
cmsg := <-channel
err = c.WriteMessage(websocket.TextMessage, []byte(cmsg))
if err != nil {
log.Println("write:", err)
break
}
}
}
}
func home(w http.ResponseWriter, r *http.Request) {
homeTemplate.Execute(w, "ws://"+r.Host+"/echo")
}
func main() {
channel := make(chan string)
switch CONN_TYPE {
case "tcp":
go tcp(channel)
case "udp":
go udp()
}
http.HandleFunc("/echo", echo(channel))
http.HandleFunc("/", home)
log.Fatal(http.ListenAndServe(":3011", nil))
}
func tcp(messageChannel chan<- string) {
fmt.Println("Hello TCP")
listener, err := net.Listen("tcp", CONN_PORT)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer listener.Close()
//messageChannel := make(chan string)
for {
// Listen for an incoming connection.
conn, err := listener.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
// Handle connections in a new goroutine.
go handleRequest(conn, messageChannel)
}
}
// Handles incoming requests.
func handleRequest(conn net.Conn, messageChannel chan<- string) {
defer conn.Close()
// Make a buffer to hold incoming data.
for {
buf := make([]byte, 2048)
// Read the incoming connection into the buffer.
_, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading:", err.Error())
break
}
json := buf
json = pretty.Pretty(json)
fmt.Println(string(json))
messageChannel <- string(json)
// Send a response back to person contacting us.
// conn.Write([]byte("You stepped into my honey pot. I'll find you! "))
conn.Write([]byte("success"))
// Close the connection when you're done with it.
}
}
func udp() {
fmt.Println("Hello!")
port := CONN_PORT
protocol := "udp"
//Build the address
udpAddr, err := net.ResolveUDPAddr(protocol, port)
if err != nil {
fmt.Println("Wrong Address")
return
}
//Output
fmt.Println("Reading " + protocol + " from " + udpAddr.String())
//Create the connection
udpConn, err := net.ListenUDP(protocol, udpAddr)
if err != nil {
fmt.Println(err)
}
//Keep calling this function
for {
handlePacket(udpConn)
}
}
func handlePacket(conn *net.UDPConn) {
var buf = make([]byte, 2048)
n, err := conn.Read(buf)
fmt.Println("Buffersize:", n)
if err != nil {
fmt.Println("Error Reading")
return
} else {
fmt.Println(string(buf))
//fmt.Println(hex.EncodeToString(buf[0:n]))
//fmt.Println("Package Done")
}
}
var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.addEventListener("load", function(evt) {
var output = document.getElementById("output");
var input = document.getElementById("input");
var ws;
var print = function(message) {
var d = document.createElement("div");
d.textContent = message;
output.appendChild(d);
};
var print2 = function(message) {
var d = document.createElement("p");
d.innerText = message;
oldNode = output.firstChild
output.replaceChild(d, oldNode)
};
document.getElementById("open").onclick = function(evt) {
if (ws) {
return false;
}
ws = new WebSocket("{{.}}");
ws.onopen = function(evt) {
print("OPEN");
}
ws.onclose = function(evt) {
print("CLOSE");
ws = null;
}
ws.onmessage = function(evt) {
print2("RESPONSE: " + evt.data);
}
ws.onerror = function(evt) {
print("ERROR: " + evt.data);
}
return false;
};
document.getElementById("send").onclick = function(evt) {
if (!ws) {
return false;
}
print("SEND: " + input.value);
ws.send(input.value);
return false;
};
document.getElementById("close").onclick = function(evt) {
if (!ws) {
return false;
}
ws.close();
return false;
};
});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server,
"Send" to send a message to the server and "Close" to close the connection.
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>
<p><input id="input" type="text" value="Hello world!">
<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output"></div>
</td></tr></table>
</body>
</html>
`))