qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
http://blog.csdn.net/friendbaby/article/details/6862741
http://bbs.csdn.net/topics/390027543
首先是初始化:
这里介绍2种方法
看看里面的server 类
class Server : public QDialog// 继承自 qdialog
{
Q_OBJECT
public:
Server(QWidget *parent = 0);// 构造函数
private slots:
void sessionOpened();
void sendFortune();
private:
QLabel *statusLabel;
QPushButton *quitButton;
QTcpServer *tcpServer;
QStringList fortunes;
QNetworkSession *networkSession;
};
看看 server 里面实现的构造函数
Server::Server(QWidget *parent): QDialog(parent), tcpServer(0), networkSession(0) // 初始化指针
{
}
整个例子的思路就是
1 tcpServer = new QTcpServer(this);
1.1 tcpServer->listen()
1.2 connect(tcpServer, SIGNAL(newConnection()), this, SLOT(sendFortune())); //在信号newConnection 里面出发接受到连接
2 QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();// 下面的代码是活的 非localhost 的ip 地址比如我现在的ip地址10.21.140.75而不是localhoust
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
3 tcpServer->serverPort()// 获得一个端口
4 当客户端连接之后 触发newConnection() 信号 ,然后 在sendFortune() 里面给 客户端发送消息:
QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); // 通过这句话获得之前和客户端建立的连接
connect(clientConnection, SIGNAL(disconnected()),clientConnection, SLOT(deleteLater()));
clientConnection->write(block);
clientConnection->disconnectFromHost();// 和本地断开