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
Windows10 VS2017 C++ Server Socket简单服务器端与客户端的更多相关文章
- iOS socket Stream 服务器端 及 客户端 演示
iOS socket Stream 测试环境,mac osx 10.8 一:建立服务器端 由于mac osx10.8 已经集成 python2和 Twisted,我们可以直接利用此,构建一个简单的so ...
- Java中使用Socket实现服务器端和客户端通讯
创建服务器端serverSocket import java.io.BufferedReader; import java.io.IOException; import java.io.InputSt ...
- C#线程池多线程Socket通讯 服务器端和客户端示例
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; ...
- 计算机网络:套接字(Socket)| Python socket实现服务器端与客户端通信,使用TCP socket阿里云ECS服务器与本机通信
所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象.一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制.从所处的地位来讲,套接字上联应 ...
- 运用socket实现简单的服务器客户端交互
Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...
- Java Socket 简单梳理
Sockets let you send raw streams of bytes back and forth between two computers, giving you fairly lo ...
- Python网络编程-Socket简单通信(及python实现远程文件发送)
学习python中使用python进行网络编程,编写简单的客户端和服务器端进行通信,大部分内容来源于网络教程,这里进行总结供以后查阅. 先介绍下TCP的三次握手: 1,简单的发送消息: 服务器端: i ...
- Python3学习之路~8.2 socket简单实例 实现ssh 发送大量数据
实例1: 利用socket模拟客户端和服务器端各自收发一次数据: #Author:Zheng Na # 客户端 import socket # 声明socket类型,同时生成socket连接对象 cl ...
- 大聊Python----通过Socket实现简单的ssh客户端
光只是简单的发消息.收消息没意思,干点正事,可以做一个极简版的ssh,就是客户端连接上服务器后,让服务器执行命令,并返回结果给客户端. #ssh_client.py import socket cli ...
随机推荐
- 常用python的标准库
1.itsdangerous # 加密签名的数据 2.re # 正则表达式 3.time # 时间模块 4.keyword # 查看关键字5.random # 随机6.uuid
- 5、Kafka生产过程分析
1.写入方式 producer采用推(push)模式将消息发布到broker, 每条消息都被追加(append)到分区(patition)中,属于顺序写磁盘(顺序写磁盘效率比随机写内存要高,保障kaf ...
- CentOS 6.5优化开机启动服务
使用chkconfig命令列举出所有服务,配合管道筛选出开机默认启动的服务,再去掉level0(关机).level4(无意义)和level6(重启)的显示,使结果更直观. chkconfig | gr ...
- 剑指offer(33)丑数
题目描述 把只包含因子2.3和5的数称作丑数(Ugly Number).例如6.8都是丑数,但14不是,因为它包含因子7. 习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数. 题目分析 ...
- CodeForces 518E Arthur and Questions(贪心 + 思维)题解
题意:给你a1~an,k,要求a1 + ... + ak < a2 + .... + ak+1 < a3 + ... + ak+2 <...,然后这里的ai有可能是?,要求你填?的数 ...
- ActiveReports 大数据分析报告:贸易争端与中国企业数字化转型
2018年11月12日至18日,亚太经合组织(APEC)领导人非正式会议首次在南太平洋最大岛国巴布亚新几内亚的首都莫尔兹比港举行,本次会议的主题是:“把握包容性机遇,拥抱数字化未来”. 面对全球不断变 ...
- 大项目小细节---onbeforeunload增强用户体验
微信公众平台编辑数据页面,点击浏览器回退按钮.刷新按钮(包括F5.Ctrl+R).关闭页面.点击其他超链接等操作的时候,会提示弹窗提示. 为增加用户体验,我们也增加类似功能. 代码如下: @if (R ...
- el-checkbox遇到的问题
在官网中有实例 <template> <el-checkbox :indeterminate="isIndeterminate" v-model="ch ...
- ES6的小知识(后半部分)
一.iterator和for-of循环 在js里有数组和对象,es6又新出现了set和map这样js就有了四种数据集合,这样可以组合使用他们,比如数组里拥有对象,set等,这样就需要一个统一的 接口机 ...
- 如何在linux下开启FTP服务
如何在linux下开启FTP服务 1. 首先服务器要安装ftp软件,查看是否已经安装ftp软件下: #which vsftpd 如果看到有vsftpd的目录说明服务器已经安装了ftp软件 2. ...