QML and Qt Quick
2021.09.18 09:41

QML에서 Websocket 서버와 통신

조회 수 5381 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄 첨부

Websocket 을 이용하면 클라이언트와 서버간에 양방향 대화형 통신을 할 수 있다. 클라이언트는 응답을 위해 폴링하지않고도 서버에 메시지를 보내거나 이벤트 기반 응답을 받을 수 있다.

QML에서 Websocket을 사용하려면 먼저 프로젝트파일에 다음줄을 추가한다.

QT += network

그리고 QML에서 QtWebSockets 모듈을 import 한다. Websocket 아이템은 일반적인 아이템 처럼 다음과 같이 사용한다.

import QtWebSockets 1.12
...
    WebSocket {
        id: client
        url: "your Websocket Server URL"
        active: true
    }
...

 

기본적으로 연결할 서버 주소 및 포트를 url 에 설정한다. ws:// 또는 wss:// 의 2가지 schemes 중 하나를 사용할 수 있으며 지정되지 않으면 ws://가 사용된다.

active 프로퍼티를 true로 설정하면 지정된 URL의 서버에 연결되며 false로 설정하면 연결이 닫힌다. 기본값은 false 다.

 

간단한 통신 예제

예제를 실행하기 위해 Websocket 서버가 필요하다. 이 글에서는 외부에 nodejs로 간단하게 구축한 websocket 서버에 연결해본다.

 

서버 측

연결이 수립되면 클라이언트에 메시지를 전송하고 클라이언트로부터의 메시지를 수신한다.

main.js

var WebSocketServer = require("ws").Server;
var wss = new WebSocketServer({ port: 3000 });

wss.on("connection", function(ws) {
ws.send("Hello! I am a server.");
ws.on("message", function(message) {
        console.log("Received: %s", message);
    });
});

 

QML 클라이언트 측

앞에서 설명한 대로 서버 URL 등을 설정하고 메시지 수신 처리 슬롯을 구현한다. 그리고 Send용 버튼을 배치하고 클릭하면 서버에 메시지를 보낸다.

main.qml

import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.12
import QtWebSockets 1.12

Window{
    visible: true
    width: 640
    height: 480
    title: "WebSocket in Qml"


    WebSocket {
        id: client
        url: "ws://XXX.XXX.XXX.XXX:3000"
        onStatusChanged: {
            if (status === WebSocket.Error) {
                console.log("Error: " + client.errorString)
            } else if (status === WebSocket.Open) {
                console.log("Open Socket")
            } else if (status === WebSocket.Closed) {
                console.log("Socket closed")
            }
        }

        onTextMessageReceived: {
            meesage.text = "Recived Message : " + message
        }

        active: true
    }

    Column {
        anchors.centerIn: parent
        spacing: 50

        Text {
            id: meesage
            anchors.horizontalCenter: parent.horizontalCenter
        }

        Button{
            anchors.horizontalCenter: parent.horizontalCenter
            text: "Send"
            onClicked: {
                client.sendTextMessage("hello makersweb.net")
            }
        }
    }
}

 

연결이 수립되고 서버에서 보낸 Text 메세지를 수신하고 화면에 출력한다. Send 버튼을 클릭하면 서버로 Text 메시지를 보낸다. 

websocket.png

 

서버에서 메시지를 잘 수신하고 출력하고 있다. 

ws_server.png

 

 

다음에는 WebSocketServer 사용법을 알아보자.

 

QML 예제 링크:

https://code.qt.io/cgit/qt/qtwebsockets.git/tree/examples/websockets?h=5.15

 

클라이언트 용 테스트 페이지:

http://livepersoninc.github.io/ws-test-page/


  1. No Image notice

    Qt프로그래밍(QtQuick) Beginner를 위한 글 읽는 순서

    Date2019.01.05 CategoryQML and Qt Quick By운영자 Views131099
    read more
  2. No Image

    clazy 로 13개의 시그널, 슬롯 오류 해결

    Date2022.08.23 CategoryGeneral and Desktop Bymakersweb Views8527
    Read More
  3. No Image

    Qt 스마트 포인터 (QSharedPointer, QScopedPointer, QPointer)

    Date2022.08.18 CategoryC++ Class Bymakersweb Views5993
    Read More
  4. Qt 6.4에 추가될 Qt Quick 3D Physics

    Date2022.08.07 CategoryQt 6 Bymakersweb Views4519
    Read More
  5. No Image

    HTTPS URL을 연결할 때 SslHandshakeFailedError 오류

    Date2022.07.31 CategoryC++ Class Bymakersweb Views5379
    Read More
  6. No Image

    단일 인스턴스 Qt 응용 프로그램(Single-instance Application)

    Date2022.06.23 CategoryGeneral and Desktop Bymakersweb Views5972
    Read More
  7. Qt로 작성된 iOS 앱에서 시리얼 통신

    Date2022.04.30 CategoryMobile and Embedded Bymakersweb Views9559
    Read More
  8. No Image

    VirtualKeyboard 스타일 커스터 마이징

    Date2022.03.13 CategoryGeneral and Desktop Bymakersweb Views5770
    Read More
  9. No Image

    성능 고려 및 제안 사항

    Date2022.03.07 Bymakersweb Views4425
    Read More
  10. No Image

    Binding 타입으로 객체 속성 간 묶기

    Date2022.03.04 CategoryQML and Qt Quick Bymakersweb Views6719
    Read More
  11. No Image

    Qt Bluetooth Low Energy 개요

    Date2022.02.13 CategoryMobile and Embedded Bymakersweb Views5697
    Read More
  12. Qt Android 앱에 AdMob 배너달기

    Date2021.12.04 CategoryMobile and Embedded Bymakersweb Views3778
    Read More
  13. No Image

    Qt 6의 C++ 프로퍼티 바인딩 예제

    Date2021.11.01 CategoryQt 6 Bymakersweb Views6814
    Read More
  14. QML에서 앵커(anchors)로 위치 지정

    Date2021.10.05 CategoryQML and Qt Quick Bymakersweb Views10019
    Read More
  15. No Image

    안드로이드용 Qt 6.2

    Date2021.10.02 CategoryQt 6 Bymakersweb Views10111
    Read More
  16. Qt 응용프로그램에서 PDF 문서 렌더링

    Date2021.09.23 CategoryGeneral and Desktop Bymakersweb Views5627
    Read More
  17. QML에서 Websocket 서버와 통신

    Date2021.09.18 CategoryQML and Qt Quick Bymakersweb Views5381
    Read More
  18. No Image

    QML 코딩 규칙

    Date2021.09.05 CategoryQML and Qt Quick Bymakersweb Views9139
    Read More
  19. QML 에서 QR코드 생성

    Date2021.08.20 CategoryQML and Qt Quick Bymakersweb Views5330
    Read More
  20. No Image

    앱을 종료할 때 QML 바인딩 오류를 피하는 방법

    Date2021.08.08 CategoryQML and Qt Quick Bymakersweb Views9788
    Read More
  21. Qt 응용프로그램에서 Lottie Animation사용

    Date2021.05.30 CategoryQML and Qt Quick Bymakersweb Views5561
    Read More
Board Pagination Prev 1 2 3 4 5 9 Next
/ 9