客户端:
#include<iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include<stdlib.h>
using namespace std;
#define BUF_SIZE 1024
int main()
{
cout << "客户端" << endl;
//设置Winsock版本,
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "error" << endl;
exit(1);
}
//创建通信套接字
SOCKET hSocket; //创建用于通信的套接字
char message[BUF_SIZE] = "hello world";
//1,创建用于通信的套接字
hSocket = socket(PF_INET, SOCK_STREAM, 0);
if (hSocket == INVALID_SOCKET)
{
cout << "socket error" << endl;
exit(1);
}
//2,连接服务器IP
SOCKADDR_IN servAdr;
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_port = htons(9999); //端口,主机转网络字节序,服务器端口
servAdr.sin_family = AF_INET; //地址族
wchar_t adr[] = L"192.168.19.1";
InetPton(AF_INET, adr, &servAdr.sin_addr); // 服务器IP地址
//3,建立连接
if (connect(hSocket, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR)
{
cout << "connect error" << endl;
return 0;
}
//4,开始循环发送
while (1)
{
int messagelen = strlen(message);
send(hSocket, message, messagelen, 0);
int Len = recv(hSocket, message, BUF_SIZE - 1, 0);
message[Len] = 0;
for (int i = 0; i < BUF_SIZE; i++)
{
cout << message[i];
}
cout << endl;
Sleep(1000);
}
//5,关闭套接字
closesocket(hSocket);
WSACleanup();
}
服务器端
#include<iostream>
#include<stdlib.h>
#include<winsock2.h>
using namespace std;
int main()
{
cout << "服务器端" << endl;
WSADATA wsaData;
SOCKET hServSock; //监听套接字
SOCKET hClntSock; //接收(accept)套接字
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "WSAStartup error" << endl;
}
//1,创建监听套接字
hServSock = socket(PF_INET, SOCK_STREAM, 0);
if (hServSock == INVALID_SOCKET)
{
cout << "申请发送套接字失败" << endl;
}
//2 ,绑定本地IP接口
SOCKADDR_IN servAdr;
memset(&servAdr, 0, sizeof(servAdr));
servAdr.sin_family = AF_INET; //地址族
servAdr.sin_port = htons(9999); //端口,主机转网络字节序
servAdr.sin_addr.s_addr = htonl(INADDR_ANY); //绑定本地IP
if (bind(hServSock, (SOCKADDR*)&servAdr, sizeof(servAdr)) == SOCKET_ERROR)
{
cout << "bind error" << endl;
}
//3, 设置监听
if (listen(hServSock, 5) == SOCKET_ERROR)
{
cout << "listen error" << endl;
}
//4, 阻塞等待客户端连接
SOCKADDR_IN clntAdr;
int clntAdrSize;
clntAdrSize = sizeof(clntAdr);
for (int i = 0; i < 5; i++)
{
hClntSock = accept(hServSock, (SOCKADDR*)&clntAdr, &clntAdrSize);
if (hClntSock == -1)
{
cout << "accept(0 error" << endl;
}
else
{
cout << "connect client " << i + 1 << endl;
char message[1024];
int strlen;
while ((strlen = recv(hClntSock, message, 1024, 0)) != 0)
{
for (int i = 0; i < strlen; i++)
{
cout << message[i];
}
cout << endl;
send(hClntSock, message, strlen, 0);
}
}
Sleep(100);
closesocket(hClntSock);
}
closesocket(hServSock);
WSACleanup();
}