2 xiaogou12138 xiaogou12138 于 2016.04.10 22:11 提问

[新手]socket 10060 各位大神帮帮我我这个小菜鸟(刚玩CSDN)

自己电脑可以,换了同学电脑就10060

/*服务端*/
#include
#include
#include
#include

#pragma comment (lib,"Ws2_32.lib")

void main()
{

//初始化socket
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2),&wsaData);

//创建socket
SOCKET listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == SOCKET_ERROR){
    printf("Error->socket(s)\n");
    exit(0);
}
printf("OK->socket(s)\n");;

//设置服务器协议,IP地址,端口
SOCKADDR_IN ServAddr;
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = inet_addr("172.30.84.37");
ServAddr.sin_port = htons(9999);

//绑定(SOCKADDR_IN->SOCKET)
if (bind(listenSocket, (SOCKADDR*)&ServAddr, sizeof(ServAddr)) == SOCKET_ERROR)
{
    printf("Error->bind(s)\n");
    exit(0);
}
printf("OK->bind(s)\n");

//监听端口
if (listen(listenSocket, 10) == SOCKET_ERROR)
{
    printf("Error->listen(s)\n");
    exit(0);
}
printf("OK->listen(s)\n");

//确认接收请求,知道成功
SOCKET acceptSocket;
while (true)
{
    if ((acceptSocket=accept(listenSocket, (SOCKADDR*)NULL, NULL))== SOCKET_ERROR)
    {
        printf("Error->accept(s)\n");
        continue;
    }
    break;

}
printf("OK->accept(s)\n");


//发送命令
char sendbuf[100];
while (scanf("%s", sendbuf))
{
    if (strcmp(sendbuf, "Bye") == 0)
        break;
    send(acceptSocket, sendbuf, strlen(sendbuf) + 1, 0);
}

closesocket(acceptSocket);
WSACleanup();
closesocket(listenSocket);

}

/*客户端*/
#include
#include
#include
#include
#include

#pragma comment (lib,"Ws2_32.lib")

void main()
{
//初始化
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

//创建socket
SOCKET connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (connectSocket==SOCKET_ERROR)
{
    printf("Error->socket(c)\n");
    exit(0);
}
printf("OK->socket(c)\n");

//设置服务器协议,IP地址,端口
SOCKADDR_IN ServAddr;
ServAddr.sin_family = AF_INET;
ServAddr.sin_addr.s_addr = inet_addr("172.30.84.37");
ServAddr.sin_port = htons(9999);

//连接服务器
if (connect(connectSocket, (SOCKADDR*)&ServAddr, sizeof(ServAddr)) == SOCKET_ERROR)
{
    printf("Error->connect(c)\n");
    exit(0);
}
printf("OK->connect(c)\n");

//接收命令

while (true)
{
    char recvbuf[100];
    int n = recv(connectSocket, recvbuf, 100, 0);
    if (n <= 0)
        break;
    printf("%d\n", n);
    recvbuf[n] = 0;
    printf("%s\n", recvbuf);
}

::Sleep(10 * 1000);
WSACleanup();
closesocket(connectSocket);

}

1个回答

devmiao
devmiao   Ds   Rxr 2016.04.10 22:36
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!