|
main.cpp
- #include <QApplication>
- #include "dialog.h"
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
- Dialog d;
- d.show();
- return app.exec();
- }
复制代码
dialog.h
- #ifndef DIALOG_H
- #define DIALOG_H
- #include <QTcpSocket>
- #include <QDialog>
- #include "ui_dialog.h"
- class Dialog: public QDialog, public Ui_Dialog
- {
- Q_OBJECT
- public:
- Dialog(QWidget *parent = 0);
- private slots:
- void sendMsg();
- void recvMsg();
- void error();
- private:
- QTcpSocket *tcpSocket;
- QString msgBuffer;
- };
- #endif
复制代码
dialog.cpp
- #include <QHostAddress>
- #include <QMessageBox>
- #include <QTextCodec>
- #include "dialog.h"
- Dialog::Dialog(QWidget *parent) : QDialog(parent)
- {
- setupUi(this);
- tcpSocket = new QTcpSocket(this);
- connect(pushButton, SIGNAL(clicked()), this, SLOT(sendMsg()));
- connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(recvMsg()));
- connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error()));
- //tcpSocket->connectToHost(QHostAddress::LocalHost, 8000);
- tcpSocket->connectToHost(QHostAddress("192.168.1.160"), 8000);
- }
- void Dialog::sendMsg()
- {
- QTextStream out(tcpSocket);
- out << lineEdit->text()<< endl;
- lineEdit->clear();
- }
- void Dialog::recvMsg()
- {
- if (!tcpSocket->canReadLine()) return;
- QString responseLine;
- do {
- QTextCodec *codec = QTextCodec::codecForName("UTF-8");
- QByteArray qba = tcpSocket->readLine();
- responseLine += codec->toUnicode(qba);
- } while (tcpSocket->canReadLine());
- msgBuffer += responseLine;
- textBrowser->setText(msgBuffer);
- textBrowser->moveCursor(QTextCursor::End);
- }
- void Dialog::error()
- {
- QMessageBox::critical(this, "socket error", tcpSocket->errorString());
- tcpSocket->close();
- }
复制代码 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|