问题描述
- [新手]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("%dn", n); recvbuf[n] = 0; printf("%sn", recvbuf); } ::Sleep(10 * 1000); WSACleanup(); closesocket(connectSocket);
}
解决方案
http://bbs.csdn.net/topics/80222568
时间: 2024-10-06 11:16:22