马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
效果:
我为了省事把服务器端跟客户端合一起了,如果要用还是得把他们分开,注意一定要先开启服务器端后开客户端才行,不然没有响应。
main.qml文件:import QtQuick 2.5
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("服务器端")
MainForm {
}
}
MainForm.ui.qml文件:import QtQuick 2.5
Rect{}
Rect.qml文件:import QtQuick 2.0
import QtWebSockets 1.0
import QtQuick.Controls 1.0
Rectangle {
width: 360
height: 360
function appendMessage(message) {
messageBox.text += "\n" + message
}
WebSocketServer {
id: server
listen: true
port:8080
onClientConnected: {
webSocket.onTextMessageReceived.connect(function(message) {//用传参接收信息
appendMessage(qsTr("Server received message: %1").arg(message));//传过来的信息
});
}
onErrorStringChanged: {
appendMessage(qsTr("Server error: %1").arg(errorString));
}
}
WebSocket {
id: socket
url: "ws://127.0.0.1:8080"
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."));
}else if (socket.status == WebSocket.Open) {
socket.sendTextMessage("Hello World");//如果接通就向接通方发送helloworld
}
}
active: true
}
Text{
id:messageBox
anchors.centerIn: parent
width:50
height: 50
}
Column{
spacing: 2
Rectangle{
width:80
height:80
border.width: 1
border.color: "green"
TextInput{
id:input
width:70
height: 50
focus:true
}
}
Button{
id:send
text:"发送"
onClicked: socket.sendTextMessage(input.text)//点击后把文本输入框里的内容发出去
}
}
}
Preview: 明天用Timer属性做一个数字时钟,还有一个小日历 |