1.初始化网络库
bool init_Socket();
bool init_Socket()
{
WSADATA wsadata;
if (0 != WSAStartup(MAKEWORD(2, 2), &wsadata)) // windows异步套接字
{
printf("启动网络库失败 %d", WSAGetLastError());
return false;
}
return true;
}
2.创建服务器socket
SOCKET create_serverSocket();
SOCKET create_serverSocket()
{
SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == fd)
{
printf("create socket error");
return INVALID_SOCKET;
}
//2.给socket 绑定IP地址和端口号
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons( PORT);
addr.sin_addr.S_un.S_addr = ADDR_ANY;
if (SOCKET_ERROR == bind(fd, (struct socketaddr*)&addr, sizeof(addr)))
{
return INVALID_SOCKET;
}
//开始监听
listen(fd, 10);
return fd;
}
3.创建客户端socket
SOCKET create_clientSocket(const char* ip)
{
SOCKET fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == fd)
{
printf("Client socket error");
return INVALID_SOCKET;
}
//2.给socket 绑定服务IP和端口号
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.S_un.S_addr = inet_addr(ip);//绑定服务器IP
if (INVALID_SOCKET == connect(fd, &addr, sizeof(addr)))
{
printf("connect error");
return INVALID_SOCKET;
}
return fd;
}
4.关闭网络库
bool close_Socket()
{
if (0 != WSACleanup())
{
printf("关闭网络库失败 %d", WSAGetLastError());
return false;
}
return true;
}
接下来是 创建服务器端 和客户端
服务器:
int main()
{
init_Socket();
SOCKET serfd = create_serverSocket();
printf("server creat successed ,wait client connect...\n");
//等待客户端连接
SOCKET clifd = accept(serfd, NULL, NULL);
if (clifd == INVALID_SOCKET)\
{
printf("连接失败");
}
printf("友好的问候一下");
//可以和客户端通信
sendFile(clifd,"../Test.txt");
closesocket(clifd);
closesocket(serfd);
close_Socket();
return 0;
}
客户端:
int main()
{
init_Socket();
SOCKET fd = create_clientSocket("127.0.0.1");
printf("连接 服务器成功。。。。");
recvFile(fd, "test.txt");
closesocket(fd);
close_Socket();
getchar();
return 0;
}
最后启动服务器 在启动客户端进行通信;
具体代码见:https://github.com/w1315/w1315https://github.com/w1315/w1315