-----QT端(先不管.h檔中的宣告),readyRead event slot---------------
void MainWindow::onReadyRead()
{
QTcpSocket* sender = static_cast<QTcpSocket*>(QObject::sender());
//從client讀入字串,因為是utf8碼,所以要用fromUtf8轉換
QByteArray datas = sender->readAll();
QString msgTxt=QString::fromUtf8(datas);
qDebug()<<"msg from client"<<msgTxt;
//回應給client
QString msg2Reply("收到");
sender->write(msg2Reply.toUtf8());
}
---------------------------------------------------------------
-----C# socket client------------------------------------------
Socket sender = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); sender.SendTimeout = 60; sender.Connect(remoteIP);
//轉成utf8碼,送到Qt socket server
string msg2Send =("Qt5.12真好用!!"); byte[] msg = System.Text.Encoding.GetEncoding("utf-8").GetBytes(msg2Send); int bytesSent = sender.Send(msg);
//讀取QtSocket server的傳回值,用utf8碼轉成字串 byte[] bytes = new byte[1024]; int bytesRec = sender.Receive(bytes); string returnMsg = Encoding.UTF8.GetString(bytes, 0, bytesRec);
sender.Shutdown(SocketShutdown.Both); sender.Close();
-------------------------------------------------
以上,大家加油了