服务端:

#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简单服务器端与客户端的更多相关文章

  1. iOS socket Stream 服务器端 及 客户端 演示

    iOS socket Stream 测试环境,mac osx 10.8 一:建立服务器端 由于mac osx10.8 已经集成 python2和 Twisted,我们可以直接利用此,构建一个简单的so ...

  2. Java中使用Socket实现服务器端和客户端通讯

    创建服务器端serverSocket import java.io.BufferedReader; import java.io.IOException; import java.io.InputSt ...

  3. C#线程池多线程Socket通讯 服务器端和客户端示例

    using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; ...

  4. 计算机网络:套接字(Socket)| Python socket实现服务器端与客户端通信,使用TCP socket阿里云ECS服务器与本机通信

    所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象.一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制.从所处的地位来讲,套接字上联应 ...

  5. 运用socket实现简单的服务器客户端交互

    Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...

  6. Java Socket 简单梳理

    Sockets let you send raw streams of bytes back and forth between two computers, giving you fairly lo ...

  7. Python网络编程-Socket简单通信(及python实现远程文件发送)

    学习python中使用python进行网络编程,编写简单的客户端和服务器端进行通信,大部分内容来源于网络教程,这里进行总结供以后查阅. 先介绍下TCP的三次握手: 1,简单的发送消息: 服务器端: i ...

  8. Python3学习之路~8.2 socket简单实例 实现ssh 发送大量数据

    实例1: 利用socket模拟客户端和服务器端各自收发一次数据: #Author:Zheng Na # 客户端 import socket # 声明socket类型,同时生成socket连接对象 cl ...

  9. 大聊Python----通过Socket实现简单的ssh客户端

    光只是简单的发消息.收消息没意思,干点正事,可以做一个极简版的ssh,就是客户端连接上服务器后,让服务器执行命令,并返回结果给客户端. #ssh_client.py import socket cli ...

随机推荐

  1. json-server基本使用

    **一.前后端并行开发的痛点** 前端需要等待后端开发完接口以后 再根据接口来完成前端的业务逻辑 **二.解决方法** 在本地模拟后端接口用来测试前端效果 这种做法称之为构建前端Mock **三.js ...

  2. RabbitMQ详解(三)------RabbitMQ的五种模式

    RabbitMQ详解(三)------RabbitMQ的五种模式 1.简单队列(模式) 上一篇文章末尾的实例给出的代码就是简单模式. 一个生产者对应一个消费者!!! pom.xml ​ 必须导入Rab ...

  3. vue elementui报错总结

    1.  错误: TypeError: _self.$scopedSlots.default is not a function 原因:这是因为在v-for/v-if切换标签时,原本这些标签每一个都是独 ...

  4. phpstorm 配置git上传代码到 码云

    方法一: 1.安装git,一路next下去. git安装完自带右键菜单 2.看一下phpstorm里的路径是否正确. 3.使用phpstorm管理代码库 新建,从码云上已有的公开项目克隆一份到本地: ...

  5. 剑指offer(19)顺时针打印矩阵

    题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2, ...

  6. gym 101081 E. Polish Fortress 几何

    E. Polish Fortress time limit per test 2.0 s memory limit per test 256 MB input standard input outpu ...

  7. MySQL5.5安装教程

                                          登录MySQL:mysql -uroot -p密码 退出MySQL:exit | quit 查看数据库:show datab ...

  8. redhat7.2安全基线BI

    (一)   Redhat linux7.2安全基线基本型(BI) 1.   密码复杂度策略 /etc/pam.d/system-auth文件中,增加内容 password requisite pam_ ...

  9. 图论++【洛谷p1744】特价采购商品&&【一本通1342】最短路径问题

    (虽然题面不是很一样,但是其实是一个题qwq) [传送门] 算法标签: 利用Floyed的o(n3)算法: (讲白了就是暴算qwq) 从任意一条单边路径开始.所有两点之间的距离是边的权,或者无穷大,如 ...

  10. CentOS6上ftp服务器搭建实战

    1.安装程序包 [root@node1 ~]$ yum install -y vsftpd[root@node1 ~]$ yum install -y lftp # 安装测试软件 2.启动vsftpd ...