Az1kuN 2016-04-10 14:11 采纳率: 0%
浏览 1625

[新手]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 2016-04-10 14:36
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器