main.qml Example File
qmlwebsocketserver/qml/qmlwebsocketserver/main.qml
import QtQuick 2.0
import QtWebSockets 1.0
Rectangle {
width: 360
height: 360
function appendMessage(message) {
messageBox.text += "\n" + message
}
WebSocketServer {
id: server
listen: true
onClientConnected: {
webSocket.onTextMessageReceived.connect(function(message) {
appendMessage(qsTr("Server received message: %1").arg(message));
webSocket.sendTextMessage(qsTr("Hello Client!"));
});
}
onErrorStringChanged: {
appendMessage(qsTr("Server error: %1").arg(errorString));
}
}
WebSocket {
id: socket
url: server.url
onTextMessageReceived: appendMessage(qsTr("Client received message: %1").arg(message))
onStatusChanged: {
if (socket.status == WebSocket.Error) {
appendMessage(qsTr("Client error: %1").arg(socket.errorString));
} else if (socket.status == WebSocket.Closed) {
appendMessage(qsTr("Client socket closed."));
}
}
}
Text {
id: messageBox
text: qsTr("Click to send a message!")
anchors.fill: parent
MouseArea {
anchors.fill: parent
onClicked: {
socket.sendTextMessage(qsTr("Hello Server!"));
}
}
}
}