Server端代码:
Client端代码:
#include <winsock2.h>
#include <stdio.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
#include <vector>
#define SIZE_BUFFER 200
int main(){
WSAData wsadata;
WSAStartup(MAKEWORD(2,0),&wsadata);
SOCKET ssocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//创建一个TCP的Socket,但是没有绑定
struct sockaddr_in server;
server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
server.sin_family = AF_INET;
server.sin_port = htons(25000);//创建一个端口地址,指定地址和端口号
if(bind(ssocket,(sockaddr*)&server,sizeof(sockaddr_in)) == SOCKET_ERROR){
std::cout<<"error bind"<<std::endl;
}//绑定TCP Socket到指定的端口地址
if(listen(ssocket, 4) == SOCKET_ERROR){
std::cout<<"listen error"<<std::endl;
}
fd_set read_fdset;//读文件描述符
std::vector<int> sockets;//读端口的集合,每监听到一个请求,就会新建一个端口,并且存放到该集合中
while(true){
FD_ZERO(&read_fdset);
FD_SET(ssocket,&read_fdset);
int n = select(0,&read_fdset,NULL,NULL,0);
if(FD_ISSET(ssocket,&read_fdset)){//如果监听端口接收到了读的请求,也就是客户端发起了请求连接
SOCKET s = accept(ssocket,NULL,0);//创建一个新的端口
if(n!=SOCKET_ERROR){
sockets.push_back(s);
FD_SET(s,&read_fdset);//将当前端口设置到FD_READ中
}
}
for(int i=0;i<sockets.size();i++){//对每一个接收端口查看是否有数据接收
char buffer[SIZE_BUFFER];
memset(buffer,0,SIZE_BUFFER);
int len = 0;
if((len = recv(sockets[i],buffer,SIZE_BUFFER,0))>0){
printf("recv size = %d, and msg = %s\n",len,buffer);
}//len:0代表客户端连接了连接,负值代表连接出错,正值代表接收数据的长度
else if(len == 0){//客户端断开连接,删除集合
sockets.erase(sockets.begin()+i);
}
}
}
system("pause");
WSACleanup();
return 0;
}
Client端代码:
#include <winsock2.h>
#include <iostream>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
int main(){
WSADATA wdata;
WSAStartup(MAKEWORD(2,0),&wdata);
SOCKADDR_IN addr;
addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
addr.sin_family = AF_INET;
addr.sin_port = htons(25000);
SOCKET cons = socket(AF_INET,SOCK_STREAM,0);
//bind(cons,(sockaddr*)&addr,0);
SOCKET s = connect(cons,(sockaddr*)&addr,sizeof(SOCKADDR_IN));
if( s == SOCKET_ERROR ){
std::cout<< s << std::endl;
}
fd_set readset,writeset,exceptset;
FD_ZERO(&writeset);
FD_SET(s,&writeset);
while(true){
select(0,&readset,&writeset,&exceptset,0);
if(FD_ISSET(s,&writeset)){
int size = send(cons,"hello",6,0);
std::cout<<"send msg size = "<<size<<std::endl;
closesocket(s);
WSACleanup();
break;
}
}
system("pause");
WSACleanup();
return 0;
}