SilenceNote
SilenceNote
2019-08-30 15:56

QT平台Socket编程问题

40
  • c++
  • c语言

我在QT开启了一个socket服务器端,逻辑是与客户端建立连接后就开启定时器不停的接受和发送数据,但是我用TCP工具创建了一个客户端测试的时候,发现连接可以建立,客户端却没有收到服务器发送的数据,求大家帮我看看是代码哪里逻辑有问题吗,第一次搞socket编程
下面先放个我的开启服务器的函数,这个函数会与客户端建立lian'jie
SOCKET CComm::StartServer()
{
//初始化WSA
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVersion, &wsaData) != 0)
{
return 0;
}

//创建套接字
SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (slisten == INVALID_SOCKET)
{
 printf("socket e"
        "rror !");
 return 0;
}

//绑定IP和端口
sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(8765);
sin.sin_addr.S_un.S_addr = inet_addr("192.168.0.107");
if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
 printf("bind error !");
}

//开始监听
if (listen(slisten, 5) == SOCKET_ERROR)
{
 printf("listen error !");
 return 0;
}

//循环接收数据
SOCKET sClient;
sockaddr_in remoteAddr;
int nAddrlen = sizeof(remoteAddr);

while (true)
{
 printf("等待连接...\n");
 sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
 if (sClient == INVALID_SOCKET)
 {
  printf("accept error !");
  continue;
 }
 printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
 break;
}

int SendTimeout = 1000;   //1000ms
int RecvTimeout = 1000;   //1000ms
setsockopt(sClient, SOL_SOCKET, SO_RCVTIMEO, (char *)&RecvTimeout, sizeof(int));
setsockopt(sClient, SOL_SOCKET, SO_SNDTIMEO, (char *)&SendTimeout, sizeof(int));
connectState = true;

return sClient;

}

然后就是运行QT程序
开启服务器成功后,再开启定时器定时接收
/***********建立本地服务器*******/
void Dialog::on_Btn_StartServer_clicked()
{
SOCKET testsClient = test.StartServer();

if(connectState == true && flag == 0)
 {
     //和上位机通讯的定时器//
    _TCPServerTimeout = new QTimer(this);
    _TCPServerTimeout->start(90);
    connect(_TCPServerTimeout, SIGNAL(timeout()), this, SLOT(_onTCPServerTimeout()));
     flag = 1;
 }

}

void Dialog::_onTCPServerTimeout()
{
int ret;
const char * sendData = "测试,接收到TCP客户端消息!\n";
char revData[255];

while (true)
{
//接收数据
ret = recv(testsClient, revData, 255, 0);
if (ret > 0)
{
 revData[ret] = 0x00;
}

send(testsClient, sendData, strlen(sendData), 0);
}

}

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答

为你推荐

换一换