代码拉取完成,页面将自动刷新
#include "myserver.h"
MyServer::MyServer(QObject *parent) : QTcpServer(parent)
{
client_count=new int(0);
qDebug()<<*client_count;
}
MyServer::~MyServer()
{
delete client_count;
}
void MyServer::start_listen(const QString port)
{
if(listen(QHostAddress::Any,port.toUInt()))
{
qDebug()<<"监听成功!";
}
else
qDebug()<<"监听失败!";
}
void MyServer::incomingConnection(qintptr socketDescriptor)
{
My_TcpClientSocket* mytcpclientsocket=new My_TcpClientSocket;
//只要有新的连接就生成一个新的通信套接字
TcpClientSocket* tcpClientSocket=new TcpClientSocket;
//将新创建的通信套接字描述符指定为参数socketDescriptor
tcpClientSocket->setSocketDescriptor(socketDescriptor);
(*client_count)++;
QString str("第"+QString::number(*client_count)+"个客户端");
mytcpclientsocket->socket_name=str;
mytcpclientsocket->m_tcpClientSocket=tcpClientSocket;
//将这个套接字加入客户端套接字列表中
m_tcpClientSocketList.append(mytcpclientsocket);
//qDebug()<<tcpClientSocket;
//接收到tcpclientsocket发送过来的消息
connect(tcpClientSocket,SIGNAL(sigUpdateSever(QString)),this,SLOT(slotUpdateServer(QString)));
//处理客户端掉线
connect(tcpClientSocket,SIGNAL(sigClientDisconnect(qintptr)),this,SLOT(slotClientDisconnected(qintptr)));
qDebug()<<"连接成功";
emit send_socketname(str);
}
void MyServer::sendtoClient(QString socketname,QString msg)
{
QByteArray ba;
ba.append(msg);
for(auto i:m_tcpClientSocketList)
{
if(i->socket_name==socketname)
i->m_tcpClientSocket->write(ba);
}
}
void MyServer::slotUpdateServer(QString sMsg)
{
//sMsg就是服务端从客户端收到的消息
//在这里对消息进行处理,根据需求来设计
emit send_message(sMsg);
}
void MyServer::slotClientDisconnected(qintptr iSocketDescriptor)
{
//如果有客户端断开连接,就将列表中的套接字删除
for(auto i:m_tcpClientSocketList)
{
if(i->m_tcpClientSocket->socketDescriptor()==iSocketDescriptor)
{
m_tcpClientSocketList.removeAt(m_tcpClientSocketList.indexOf(i));
delete i->m_tcpClientSocket;
delete i;
//qDebug()<<"已释放内存";
return;
}
}
return;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。