Windows10 VS2017 C++ Server Socket簡單伺服器端與客戶端
服務端:
#include "pch.h"
#include<iostream>
#include<WinSock2.h>
#include <Ws2tcpip.h>
#define CONNECT_NUM_MAX 10
#pragma comment(lib, "ws2_32.lib")
using namespace std;
int main()
{
//載入套接字型檔
WSADATA wsaData;
int iRet = 0;
iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iRet != 0)
{
cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;;
return -1;
}
if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
{
WSACleanup();
cout << "WSADATA version is not correct!" << endl;
return -1;
}
//建立套接字
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
{
cout << "serverSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
return -1;
}
//初始化伺服器地址族變數
SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(6000);
//繫結
iRet = bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR));
if (iRet == SOCKET_ERROR)
{
cout << "bind(serverSocket, (SOCKADDR*)&addrSrv, sizeof(SOCKADDR)) execute failed!" << endl;
return -1;
}
//監聽
iRet = listen(serverSocket, CONNECT_NUM_MAX);
if (iRet == SOCKET_ERROR)
{
cout << "listen(serverSocket, 10) execute failed!" << endl;
return -1;
}
else
{
cout << "Server is listening on " << addrSrv.sin_addr.S_un.S_addr << ":" << addrSrv.sin_port << "." << endl;
}
//等待連線_接收_傳送
SOCKADDR_IN clientAddr;
int len = sizeof(SOCKADDR);
while (1)
{
SOCKET connSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &len);
if (connSocket == INVALID_SOCKET)
{
cout << "accept(serverSocket, (SOCKADDR*)&clientAddr, &len) execute failed!" << endl;
return -1;
}
else
{
cout << "Connection established! Waiting for messages." << endl;
}
int x = 0;
while (true)
{
//接收訊息
char recvBuf[100];
int sig = recv(connSocket, recvBuf, 100, 0);
//沒有連線時斷開
if (sig <= 0)
{
printf("Error: Lost connection!\n");
break;
}
printf("%s\n", recvBuf);
//傳送訊息
char sendBuf[100];
//sprintf_s(sendBuf, "Welcome %s", inet_ntoa(clientAddr.sin_addr));
char str[INET_ADDRSTRLEN];
sprintf_s(sendBuf, "Welcome! client from %s %d!", inet_ntop(AF_INET, &clientAddr.sin_addr, str, sizeof(str)), x);
send(connSocket, sendBuf, strlen(sendBuf) + 1, 0);
x++;
}
//關閉連線
closesocket(connSocket);
}
system("pause");
return 0;
}
多執行緒服務端:
server.h
#ifndef SERVER_H
#define SERVER_H
#include <Winsock2.h>
#include <windows.h>
#pragma comment (lib, "ws2_32.lib")
#define IP_BUF_SIZE 129
class Server
{
public:
Server();
~Server();
Server(const Server &) = delete;
Server & operator=(const Server &) = delete;
void WaitForClient();
private:
WORD winsock_ver;
WSADATA wsa_data;
SOCKET sock_svr;
SOCKET sock_clt;
HANDLE h_thread;
SOCKADDR_IN addr_svr;
SOCKADDR_IN addr_clt;
int ret_val;
int addr_len;
PWSTR buf_ip[IP_BUF_SIZE];
};
#endif
#include <iostream>
#include <WS2tcpip.h>
using std::cerr;
using std::cout;
using std::endl;
#define SERVER_PORT 6000
#define MSG_BUF_SIZE 1024
Server::Server()
{
cout << "Initializing server...\n";
//
winsock_ver = MAKEWORD(2, 2);
addr_len = sizeof(SOCKADDR_IN);
addr_svr.sin_family = AF_INET;
addr_svr.sin_port = ::htons(SERVER_PORT);
addr_svr.sin_addr.S_un.S_addr = ADDR_ANY;
memset(buf_ip, 0, IP_BUF_SIZE);
//
ret_val = ::WSAStartup(winsock_ver, &wsa_data);
if (ret_val != 0)
{
cerr << "WSA failed to start up!Error code: " << ::WSAGetLastError() << "\n";
system("pause");
exit(1);
}
cout << "WSA started up successfully...\n";
//
sock_svr = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock_svr == INVALID_SOCKET)
{
cerr << "Failed to create server socket!Error code: " << ::WSAGetLastError() << "\n";
::WSACleanup();
system("pause");
exit(1);
}
cout << "Server socket created successfully...\n";
//
ret_val = ::bind(sock_svr, (SOCKADDR*)&addr_svr, addr_len);
if (ret_val != 0)
{
cerr << "Failed to bind server socket!Error code: " << ::WSAGetLastError() << "\n";
::WSACleanup();
system("pause");
exit(1);
}
cout << "Server socket bound successfully...\n";
//
ret_val = ::listen(sock_svr, SOMAXCONN);
if (ret_val == SOCKET_ERROR)
{
cerr << "Server socket failed to listen!Error code: " << ::WSAGetLastError() << "\n";
::WSACleanup();
system("pause");
exit(1);
}
cout << "Server socket started to listen...\n";
//
cout << "Server started successfully..." << endl;
}
Server::~Server()
{
::closesocket(sock_svr);
::closesocket(sock_clt);
::WSACleanup();
cout << "Socket closed..." << endl;
}
DWORD WINAPI CreateClientThread(LPVOID lpParameter);
//
void Server::WaitForClient()
{
while (true)
{
sock_clt = ::accept(sock_svr, (SOCKADDR*)&addr_clt, &addr_len);
if (sock_clt == INVALID_SOCKET)
{
cerr << "Failed to accept client!Error code: " << ::WSAGetLastError() << "\n";
::WSACleanup();
system("pause");
exit(1);
}
::InetNtop(addr_clt.sin_family, &addr_clt, *buf_ip, IP_BUF_SIZE);
cout << "A new client connected...IP address: " << buf_ip << ", port number: " << ::ntohs(addr_clt.sin_port) << endl;
h_thread = ::CreateThread(nullptr, 0, CreateClientThread, (LPVOID)sock_clt, 0, nullptr);
if (h_thread == NULL)
{
cerr << "Failed to create a new thread!Error code: " << ::WSAGetLastError() << "\n";
::WSACleanup();
system("pause");
exit(1);
}
::CloseHandle(h_thread);
}
}
DWORD WINAPI CreateClientThread(LPVOID lpParameter)
{
SOCKET sock_clt = (SOCKET)lpParameter;
char buf_msg[MSG_BUF_SIZE];
int ret_val = 0;
int snd_result = 0;
do
{
memset(buf_msg, 0, MSG_BUF_SIZE);
ret_val = ::recv(sock_clt, buf_msg, MSG_BUF_SIZE, 0);
if (ret_val > 0)
{
if (strcmp(buf_msg, "exit") == 0)
{
cout << "Client requests to close the connection..." << endl;
break;
}
cout << "Message received: " << buf_msg << endl;
snd_result = ::send(sock_clt, buf_msg, MSG_BUF_SIZE, 0);
if (snd_result == SOCKET_ERROR)
{
cerr << "Failed to send message to client!Error code: " << ::GetLastError() << "\n";
::closesocket(sock_clt);
system("pause");
return 1;
}
}
else if (ret_val == 0)
{
cout << "connection closed..." << endl;
}
else
{
cerr << "Failed to receive message from client!Error code: " << ::GetLastError() << "\n";
::closesocket(sock_clt);
system("pause");
return 1;
}
} while (ret_val > 0);
//
ret_val = ::shutdown(sock_clt, SD_SEND);
if (ret_val == SOCKET_ERROR)
{
cerr << "Failed to shutdown the client socket!Error code: " << ::GetLastError() << "\n";
::closesocket(sock_clt);
system("pause");
return 1;
}
return 0;
}
server.cpp
#include "pch.h"
#include "server.h"
int main()
{
Server svr;
svr.WaitForClient();
system("pause");
return 0;
}
客戶端:
#include "pch.h"
#include<iostream>
#include <winsock2.h>
#include <Ws2tcpip.h>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
int main()
{
//載入套接字型檔
WSADATA wsaData;
int iRet = 0;
iRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iRet != 0)
{
cout << "WSAStartup(MAKEWORD(2, 2), &wsaData) execute failed!" << endl;
return -1;
}
if (2 != LOBYTE(wsaData.wVersion) || 2 != HIBYTE(wsaData.wVersion))
{
WSACleanup();
cout << "WSADATA version is not correct!" << endl;
return -1;
}
//建立套接字
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == INVALID_SOCKET)
{
cout << "clientSocket = socket(AF_INET, SOCK_STREAM, 0) execute failed!" << endl;
return -1;
}
//初始化伺服器端地址族變數
SOCKADDR_IN srvAddr;
//srvAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
inet_pton(AF_INET, "127.0.0.1", &srvAddr.sin_addr);
srvAddr.sin_family = AF_INET;
srvAddr.sin_port = htons(6000);
//連線伺服器
iRet = connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR));
if (0 != iRet)
{
cout << "connect(clientSocket, (SOCKADDR*)&srvAddr, sizeof(SOCKADDR)) execute failed!" << endl;
return -1;
}
int x = 0;
while (true)
{
x++;
//傳送訊息
char sendBuf[100];
sprintf_s(sendBuf, "Hello, this is client %s %d!", "bunny", x);
printf(sendBuf);
printf("\n");
send(clientSocket, sendBuf, strlen(sendBuf) + 1, 0);
//接收訊息
char recvBuf[100];
int sig = recv(clientSocket, recvBuf, 100, 0);
//沒有連線時斷開
if (sig <=0)
{
printf("Error: Lost connection!\n");
break;
}
printf("%s\n", recvBuf);
//跳出
if (x==20)
{
break;
}
Sleep(3000);
}
//清理
closesocket(clientSocket);
WSACleanup();
system("pause");
return 0;
}
參考地址:
https://www.cnblogs.com/darren45/p/4818867.html
https://blog.csdn.net/zyy617532750/article/details/58595700/
https://www.cnblogs.com/jzincnblogs/p/5189636.html
https://blog.csdn.net/s_lisheng/article/details/74502795
相關文章
- C++客戶端程式(socket)C++客戶端
- Linux下簡單的ACE socket客戶端和伺服器端Linux客戶端伺服器
- Socket最簡單的客戶端與服務端通訊-Java客戶端服務端Java
- socket.io 客戶端與伺服器應用客戶端伺服器
- 【windows socket+TCP伺服器客戶端】WindowsTCP伺服器客戶端
- 【windows socket+UDP伺服器客戶端】WindowsUDP伺服器客戶端
- 【windows socket+HTTP伺服器客戶端】WindowsHTTP伺服器客戶端
- C#Socket伺服器與客戶端的開發(3)C#伺服器客戶端
- 客戶端與服務端Socket通訊原理詳解客戶端服務端
- Python socket的客戶端Python客戶端
- 如何用Java Socket實現一個簡單的Redis客戶端JavaRedis客戶端
- WebSocket簡單使用(二)-客戶端Web客戶端
- 簡單的C++檔案伺服器--Linux C++客戶端從服務端獲取檔案C++伺服器Linux客戶端服務端
- Java Socket程式設計系列(三)開發支援單客戶端訪問的ServerJava程式設計客戶端Server
- C/S(socket、執行緒 實現多個客戶端、伺服器端簡易通訊)執行緒客戶端伺服器
- 客戶端的socket是否需要bind?客戶端
- oracle 客戶端與伺服器端的關係Oracle客戶端伺服器
- js 客戶端與伺服器端的通訊JS客戶端伺服器
- ElasticSearch客戶端簡單操作例項Elasticsearch客戶端
- github客戶端fork的簡單教程Github客戶端
- php原生socket實現客戶端與服務端資料傳輸PHP客戶端服務端
- zeroc ice 客戶端與服務端通訊例子(c++)客戶端服務端C++
- windows socket簡單使用--實現客戶端連結服務端併傳送和接收資料Windows客戶端服務端
- binder通訊例項之c++客戶端與c++服務端C++客戶端服務端
- Linux網路程式設計之socket簡單通訊--客戶端程式碼Linux程式設計客戶端
- SHA-256加密簡單例項(客戶端、服務端)加密單例客戶端服務端
- 記筆記:C# Socket客戶端監聽伺服器端處理方案【同步】筆記C#客戶端伺服器
- 【2】Windows C++ Redis服務端搭建與客戶端開發WindowsC++Redis服務端客戶端
- .net socket.io客戶端使用過程客戶端
- redis伺服器/客戶端安裝與配置Redis伺服器客戶端
- Easyvision中的伺服器與客戶端伺服器客戶端
- 修改CAS客戶端 使用簡單HTTP協議客戶端HTTP協議
- TCP通訊客戶端和服務端簡單程式碼實現TCP客戶端服務端
- 利用tirpc庫實現簡單的客戶端和服務端RPC客戶端服務端
- Windows網路程式設計附書程式碼(簡單的伺服器與客戶端)Windows程式設計伺服器客戶端
- linux網路程式設計之用socket實現簡單客戶端和服務端的通訊(基於TCP)Linux程式設計客戶端服務端TCP
- 基於node的tcp客戶端和服務端的簡單通訊TCP客戶端服務端
- YUM源伺服器搭建與客戶端配置使用伺服器客戶端