2 qianhangkang qianhangkang 于 2016.02.27 11:11 提问

新手关于socket的小问题 各位大大来看看谢谢啦.。

socket的通信中 client端接受的消息总是慢一拍怎么回事图片说明

7个回答

shaosheng2008
shaosheng2008   2016.02.27 12:30
已采纳

原因是多了'\n':
scanf("%s\n", cmd);
改成
scanf("%s", cmd);
也是OK的

qianhangkang
qianhangkang 恩,谢谢,解决了,但是为什么会这样?
接近 2 年之前 回复
qianhangkang
qianhangkang 我试试,不过为什么多了换行符就会这样?
接近 2 年之前 回复
qianhangkang
qianhangkang   2016.02.27 11:12

服务端代码:
#include "stdafx.h"
#include
#include
#pragma comment(lib,"ws2_32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
BOOL bret = false;
do
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
if (2 != LOBYTE(wsadata.wVersion) || 2 != HIBYTE(wsadata.wVersion))
break;

    SOCKET socksever;
    socksever = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (INVALID_SOCKET == socksever)
        break;

    sockaddr_in addrsever = { 0 };
    addrsever.sin_family = AF_INET;
    addrsever.sin_port = htons(8383);

    if (SOCKET_ERROR == bind(socksever, (SOCKADDR*)&addrsever, sizeof(addrsever)))
        break;


    if (SOCKET_ERROR == listen(socksever, 5))
        break;
    SOCKET sockclient;
    sockclient= accept(socksever, nullptr, nullptr);
    if (INVALID_SOCKET == socksever)
        break;

    char cmd[MAXBYTE] = { 0 };      
    while (true)
    {
        printf("please input your cmd:\n");
        scanf("%s\n", cmd);
        send(sockclient, cmd, strlen(cmd)+1, 0);

    }
    system("pause");
    bret = true;
} while (false);
WSACleanup();
return 0;

}

qianhangkang
qianhangkang   2016.02.27 11:13

这是客户端的:
#include "stdafx.h"
#include
#include
#include
#pragma comment (lib,"ws2_32.lib")

int _tmain(int argc, _TCHAR* argv[])
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
if (2 != LOBYTE(wsadata.wVersion) || 2 != HIBYTE(wsadata.wVersion))
exit(0);

    SOCKET sockclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (INVALID_SOCKET == sockclient)
        exit(0);

    sockaddr_in addsever = { 0 };
    addsever.sin_family = AF_INET;
    addsever.sin_port = htons(8383);
    addsever.sin_addr.S_un.S_addr = inet_addr("192.168.23.7");

    if (SOCKET_ERROR == connect(sockclient, (SOCKADDR*)&addsever, sizeof(addsever)))
        exit(0);
    printf("call succeed\n");

    int recvlen = { 0 };
    char message[MAXBYTE] = { 0 };
    while (true)
    {
    recvlen=recv(sockclient, message,MAXBYTE,0);
    if (recvlen>0)
    {
        printf(message);
        printf("\n");
    }
    }

WSACleanup();
return 0;

}

qianhangkang
qianhangkang   2016.02.27 11:13

谢谢各位大大,帮小生一看

qianhangkang
qianhangkang   2016.02.27 11:13

谢谢各位大大,帮小生一看

shaosheng2008
shaosheng2008   2016.02.27 12:23

scanf("%s\n", cmd);
把这个换成以下的语句试试(头文件增加 #include ):
std::cin>>cmd;

Royal_lr
Royal_lr   Ds   Rxr 2016.02.27 13:20

客户端接受的消息本来就是通过服务端转发的信息,,

qianhangkang
qianhangkang 但是为什么我的慢一拍。。。
接近 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片