c++ socket编程 服务器/客户端

 ​

实现: 客户端往服务器端发送一条数据,服务器端接收数据并也发送一条数据给客户端。

废话少说 直接上代码

[文字描述都写在注释]

服务器实现

#include "stdafx.h"
#include <iostream>
#include "windows.h" //一定要包含该头文件
using namespace std;
#pragma comment(lib, "WS2_32.lib") //显示加载 ws2_32.dll ws2_32.dll就是最新socket版本

int main()
{
cout << "-----------服务器-----------" << endl;

//套接字初始化
WSADATA wsaData; //这个结构被用来存储被WSAStartup函数调用后返回的 Windows Sockets 数据。
WORD sockVersion = MAKEWORD(2, 2); //windows网络编程库的版本号信息
if (WSAStartup(sockVersion, &wsaData) != 0) //WSAStartup函数是在程序中初始化并加载Windows网络
{
cout << "套接字初始化失败!" << endl;
return 0;
}

//创建服务器套接字
SOCKET SeverSocket;
if ((SeverSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "套接字创建失败!" << endl;
return 0;
}
struct sockaddr_in SeverAddress; //一个绑定地址:有IP地址,有端口号,有协议族
memset(&SeverAddress, 0, sizeof(sockaddr_in)); //初始化结构体
SeverAddress.sin_family = AF_INET;
SeverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//填入本机IP地址
SeverAddress.sin_port = htons(60000);//设定端口号

//绑定套接字 指定绑定的IP地址和端口号
if (bind(SeverSocket, (sockaddr*)&SeverAddress, sizeof(SeverAddress)) == SOCKET_ERROR)
{
cout << "套接字绑定失败!"<<endl;
return 0;
}

//服务器监听
if (listen(SeverSocket, SOMAXCONN) == SOCKET_ERROR) //监听的第二个参数就是:能存放多少个客户端请求,到并发编程的时候很有用
{
cout << "监听失败!"<<endl;
return 0;
}
else
cout << "服务器正在监听:"<<endl;

//服务器接受连接请求
sockaddr_in revClientAddress; //套接字的地址,端口
SOCKET revClientSocket = INVALID_SOCKET; //用来接收客户端连接
//memset(&revClientAddress, 0, sizeof(revClientAddress));
int addlen = sizeof(revClientAddress);
if ((revClientSocket = accept(SeverSocket, (sockaddr*)&revClientAddress, &addlen)) == INVALID_SOCKET)
{
cout << "接受客户端连接失败!" << endl;
return 0;
}
else
cout << "接受客户端连接成功!"<<endl;

//服务器接受数据
char recvbuf[2048] = {};
if ( recv(revClientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败!" <<WSAGetLastError()<< endl;
return 0;
}
else
cout << "服务器接收的数据:" << recvbuf << endl;

//服务器发送数据
char sendbuf[2048] = "from server:hello client.";
if (send(revClientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}
//关闭socket
closesocket(revClientSocket);
closesocket(SeverSocket);

//终止
WSACleanup();
cout << "服务器停止!" << endl;
return 0;
}

客户端实现

在这里再提醒一点,运行程序的时候,我们是先运行服务端程序,再运行客户端程序.

所以有些同学可能会说"我们的代码都一样啊!怎么到我这就不成功了呢?",这是一个

低级的错误,我们要避免。

#include "stdafx.h"
#include "windows.h"
#include "iostream"
using namespace std;
#pragma comment(lib, "ws2_32.lib")


int main()
{
cout << "-----------客户端-----------" << endl;
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "套接字初始化失败!"<<endl;
}
SOCKET clientSocket;
if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "套接字创建失败!"<<endl;
}
struct sockaddr_in SeverAddress; //服务器地址 也就是即将要连接的目标地址
memset(&SeverAddress, 0, sizeof(sockaddr_in));
SeverAddress.sin_family = AF_INET;
SeverAddress.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //127.0.0.1表示本机ip地址
SeverAddress.sin_port = htons(60000);//设定端口号

//开始连接
if (connect(clientSocket, (sockaddr*)&SeverAddress, sizeof(SeverAddress)) == SOCKET_ERROR)
{
cout << "客户端:和服务器连接失败!"<<endl;
return 0;
}
else
cout << "客户端:与服务器连接成功!" << endl;

//客户端发送数据给服务器
char sendbuf[2048] = "from client:hello server.";
if (send(clientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}

//客户端接受来自服务器的数据
char recvbuf[2048] = {};
if (recv(clientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败" << endl;
}
else
cout << "客户端接收的数据:" << recvbuf << endl;

// 关闭socket
if (clientSocket != INVALID_SOCKET) {
closesocket(clientSocket);
clientSocket = INVALID_SOCKET;
}

// 终止
WSACleanup();
cout << "客户端退出!" << endl;
return 0;
}

运行结果如下

c++网络编程:实现简单的聊天——基于服务器/客户端的模式_网络

现在来实现较为自由的聊天

上面代码只是将缓冲区的数据发送出去,可以改为把从键盘输入的数据发送出去,即实现更”自由“的聊天。先来看第一种实现的方法。

代码主体部分不变,在数据传输部分加一个while循环即可。

服务器

while (1)
{
//服务器接受数据
char recvbuf[2048] = {}; //接收缓冲区
if (recv(revClientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败!" << WSAGetLastError() << endl;
return 0;
}
else
cout << "服务器接收的数据:" << recvbuf << endl;

//服务器发送数据
char sendbuf[2048] = {}; //发送缓冲区
cin.getline(sendbuf, 2048);
if (send(revClientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}
}

客户端

while (1)
{
//客户端发送数据给服务器
char sendbuf[2048] = {}; //发送缓冲区
cin.getline(sendbuf, 2048);
if (send(clientSocket, sendbuf,strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}

//客户端接受来自服务器的数据
char recvbuf[2048] = {}; //接收缓冲区
if (recv(clientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败" << endl;
}
else
cout << "客户端接收的数据:" << recvbuf << endl;
}

效果图

c++网络编程:实现简单的聊天——基于服务器/客户端的模式_socket_02

但是这样存在问题,由于while循环中,接收和发送总是按顺序进行,无法同时进行,因此只能轮流说话,一人说一句。从客户端开始。究其原因是因为send()、recv()是拥塞函数!

实现自由聊天

针对上面的问题进一步做出改进,为了程序能够同时进行接受和发送,使用多线程。

服务器

#include "stdafx.h"
#include <iostream>
#include "windows.h" //一定要包含该头文件
#include "process.h"
#include <string>
using namespace std;
#pragma comment(lib, "WS2_32.lib") //显示加载 ws2_32.dll ws2_32.dll就是最新socket版本

void Receive(void *param) //接受数据的线程函数
{
while (1)
{
//服务器接受数据
SOCKET revClientSocket = *(SOCKET*)(param);
char recvbuf[2048] = {}; //接收缓冲区
if (recv(revClientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败!" << endl;
}
else
cout << "【客户端】说:" << recvbuf << endl;
}
}

void Send(void *param) //发送数据的线程函数
{
while (1)
{
//服务器发送数据
SOCKET revClientSocket = *(SOCKET*)(param);
char sendbuf[2048] = {}; //发送缓冲区
cin.getline(sendbuf, 2048);
if (send(revClientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!" << endl;
}
else
cout << "【自己】说:" << sendbuf << endl;
}
}

int main()
{
cout << "-----------服务器-----------" << endl;

//套接字初始化
WSADATA wsaData; //这个结构被用来存储被WSAStartup函数调用后返回的 Windows Sockets 数据。
WORD sockVersion = MAKEWORD(2, 2); //windows网络编程库的版本号信息
if (WSAStartup(sockVersion, &wsaData) != 0) //WSAStartup函数是在程序中初始化并加载Windows网络
{
cout << "套接字初始化失败!" << endl;
return 0;
}

//创建服务器套接字
SOCKET SeverSocket;
if ((SeverSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "套接字创建失败!" << endl;
return 0;
}
struct sockaddr_in SeverAddress; //一个绑定地址:有IP地址,有端口号,有协议族
memset(&SeverAddress, 0, sizeof(sockaddr_in)); //初始化结构体
SeverAddress.sin_family = AF_INET;
SeverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//填入本机IP地址
SeverAddress.sin_port = htons(60000);//设定端口号

//绑定套接字 指定绑定的IP地址和端口号
if (bind(SeverSocket, (sockaddr*)&SeverAddress, sizeof(SeverAddress)) == SOCKET_ERROR)
{
cout << "套接字绑定失败!"<<endl;
return 0;
}

//服务器监听
if (listen(SeverSocket, SOMAXCONN) == SOCKET_ERROR) //监听的第二个参数就是:能存放多少个客户端请求,到并发编程的时候很有用
{
cout << "监听失败!"<<endl;
return 0;
}
else
cout << "服务器正在监听:"<<endl;

//服务器接受连接请求
sockaddr_in revClientAddress; //套接字的地址,端口
SOCKET revClientSocket = INVALID_SOCKET; //用来接收客户端连接
//memset(&revClientAddress, 0, sizeof(revClientAddress));
int addlen = sizeof(revClientAddress);
if ((revClientSocket = accept(SeverSocket, (sockaddr*)&revClientAddress, &addlen)) == INVALID_SOCKET)
{
cout << "接受客户端连接失败!" << endl;
return 0;
}
else
cout << "接受客户端连接成功!"<<endl;

//创建两个子线程
_beginthread(Receive, 0, &revClientSocket);
_beginthread(Send, 0, &revClientSocket);

while (1){} //为了避免主线程退出使子线程被迫消亡,使主线程进入循环

//关闭socket
closesocket(revClientSocket);
closesocket(SeverSocket);

//终止
WSACleanup();
cout << "服务器停止!" << endl;
return 0;
}

客户端

#include "stdafx.h"
#include "windows.h"
#include "iostream"
#include "process.h"
#include <string>
using namespace std;
#pragma comment(lib, "ws2_32.lib")

void Receive(void *param)
{
while (1)
{
//客户端接受来自服务器的数据
SOCKET clientSocket = *(SOCKET*)(param);
char recvbuf[2048] = {}; //接收缓冲区
if (recv(clientSocket, recvbuf, 2048, 0) == SOCKET_ERROR)
{
cout << "数据接受失败" << endl;
}
else
cout << "【服务器】说:" << recvbuf << endl;
}
}

void Send(void *param)
{
while (1)
{
//客户端发送数据给服务器
SOCKET clientSocket = *(SOCKET*)(param);
char sendbuf[2048] = {}; //发送缓冲区
cin.getline(sendbuf, 2048);
if (send(clientSocket, sendbuf, strlen(sendbuf), 0) == SOCKET_ERROR)
{
cout << "发送消息失败!";
}
else
cout << "【自己】说:" << sendbuf << endl;
}
}

int main()
{
cout << "-----------客户端-----------" << endl;
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0)
{
cout << "套接字初始化失败!"<<endl;
}
SOCKET clientSocket;
if ((clientSocket = socket(AF_INET, SOCK_STREAM, 0)) == SOCKET_ERROR)
{
cout << "套接字创建失败!"<<endl;
}
struct sockaddr_in SeverAddress; //服务器地址 也就是即将要连接的目标地址
memset(&SeverAddress, 0, sizeof(sockaddr_in));
SeverAddress.sin_family = AF_INET;
SeverAddress.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //127.0.0.1表示本机ip地址
SeverAddress.sin_port = htons(60000);//设定端口号

//开始连接
if (connect(clientSocket, (sockaddr*)&SeverAddress, sizeof(SeverAddress)) == SOCKET_ERROR)
{
cout << "客户端:和服务器连接失败!"<<endl;
return 0;
}
else
cout << "与服务器连接成功!" << endl;

//创建两个子线程
_beginthread(Receive, 0, &clientSocket);
_beginthread(Send, 0, &clientSocket);

Sleep(INFINITE); //这里采用另外一种技术避免主线程执行完退出——使其无限期休眠
// 关闭socket
if (clientSocket != INVALID_SOCKET) {
closesocket(clientSocket);
clientSocket = INVALID_SOCKET;
}

// 终止
WSACleanup();
cout << "客户端退出!" << endl;
return 0;
}

运行效果

c++网络编程:实现简单的聊天——基于服务器/客户端的模式_客户端_03