您的位置:首页 > 编程语言 > C语言/C++

C语言socket模拟客户和服务器通信

2016-04-04 18:56 423 查看
客户端代码:

#include <iostream>
#include <winsock2.h>
#include <string>
#define SERVER_PORT 6666
#pragma comment(lib,"ws2_32")
using namespace std;
int main(int agrn,char *agrs[]){
char server_Ip[30];
WORD mSocketVersionCode;
WSADATA wasData;
SOCKET client_Socket;
struct sockaddr_in server_addr;
int return_Num;
mSocketVersionCode = MAKEWORD(2,2);
return_Num = WSAStartup(mSocketVersionCode,&wasData);
if(LOBYTE(wasData.wVersion)!=2||LOBYTE(wasData.wVersion)!=2){
cout<<"The version of Socket if compaliable"<<endl;
return -1;

}
//创建本地Socket
client_Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(client_Socket == INVALID_SOCKET){
cout<<"Create Local Socket Failed!"<<endl;
closesocket(client_Socket);
return 0;
}
cout<<"Please input the ip of the server!:";
cin>>server_Ip;
//构建服务器地址信息
server_addr.sin_family = AF_INET;
server_addr.sin_port = ntohs(SERVER_PORT);
server_addr.sin_addr.S_un.S_addr = inet_addr(server_Ip);
//连接服务器
return_Num = connect(client_Socket,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(return_Num == SOCKET_ERROR){
cout<<"Connet Failed"<<endl;
closesocket(client_Socket);
WSACleanup();
return 0;
}else{
cout<<"Connect Successfully!"<<endl;
}
char buff[1024];
cout<<"Please input the message to send to the server:";
cin>>buff;
return_Num = send(client_Socket,buff,sizeof(buff),0);
if(return_Num == SOCKET_ERROR){
cout<<"Send Failed!"<<endl;
closesocket(client_Socket);
WSACleanup();
return -1;
}else{
cout<<"Send Successfully!" <<endl;
}
cout<<"Again: Please input the message to send to the server:";
cin>>buff;
return_Num = send(client_Socket,buff,sizeof(buff),0);
if(return_Num == SOCKET_ERROR){
cout<<"Send Failed!"<<endl;
closesocket(client_Socket);
WSACleanup();
return -1;
}else{
cout<<"Send Successfully!" <<endl;
}
return_Num = recv(client_Socket,buff,1024,0);
if(return_Num == SOCKET_ERROR){
cout<<"Receive Failed!"<<endl;
closesocket(client_Socket);
WSACleanup();
return -1;
}else{
cout<<"Receive Successfully!" <<endl;
}
cout<<"The information Receive :";
cout<<buff<<endl;
return 0;
}


服务器端代码:

#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#define SERVER_PORT 6666
#pragma comment(lib, "ws2_32")
/*
关于WSAStartup方法和WSACleanup方法引用出错的解决:
错误:
编译的时候出现
undefined reference to `__imp_WSAStartup'
undefined reference to `__imp_WSACleanup'
在一般编译器中不会直接连接编译wsock动态库,需要手动添加库
首先可以尝试代码中直接引入动态库,#pragam comment(lib,"ws2_32");
如果不行再手动添加库
在vc中,点项目(project-->project option)在makefile中输入-L"ws2_32"
在dvc C++中点击工具(Tool)-->编译选项(Compile Option)在编译命令框中输入-lwsokt
*/
using namespace std;
int main()
{
int produrce_Step = 0;
WORD winSocketVersion;
WSADATA wsaDATA;
SOCKET listen_Socket,server_Socket;
struct sockaddr_in client_socket_addr;  //客户端地址信息
struct sockaddr_in ser_socket_addr;  	//服务器端地址信息
winSocketVersion = MAKEWORD(2,2);
int return_num;
//WinSocket 初始化
return_num = WSAStartup(winSocketVersion,&wsaDATA);
if(return_num!=0){
cout<<"WSAStartup() failed!"<<endl;
return 0;
}
//确认支持winsocket版本2.2
if(LOBYTE(wsaDATA.wVersion)!=2||HIBYTE(wsaDATA.wVersion)!=2){
WSACleanup();
cout<<"Invalid WinSockt Version!"<<endl;
return 0;
}
produrce_Step ++;
cout<<produrce_Step<<"***Initial WinSocket Successfully!"<<endl;
//创建本地Socket
server_Socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//采用tcp协议创建端口
//注意这里的protocol flag的值可以为0,因为AF_INET搭配SOCKET_STREAM默认采用tcp协议
if(server_Socket==INVALID_SOCKET){//如果创建Socket失败
WSACleanup();
cout<<"Create Socket failed!"<<endl;
return 0;
}else{
cout<<++produrce_Step<<"***Create local Socket successfully!"<<endl;
}
//构建服务器本地地址信息
ser_socket_addr.sin_family = AF_INET;  //地址家族sin_family,一般Tcp/ip地址家族为AF_INET
ser_socket_addr.sin_port = htons(SERVER_PORT);//将端口号转化为网络字节
ser_socket_addr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//使用INADDR_ANY指定任意地址
//INADDR_ANY就是指定地址为0.0.0.0的地址,这个地址事实上表示不确定地址,
//或“所有地址”、“任意地址”。 一般来说,在各个系统中均定义成为0值。
cout<<++produrce_Step<<"***Finish the Initial of local Address Information"<<endl;
//为Socket绑定端口port
return_num = bind(server_Socket,(struct sockaddr*)&ser_socket_addr,sizeof(ser_socket_addr));
if(return_num == SOCKET_ERROR){
cout<<"Bind the port failed, the Socket has been closed!"<<endl;
cout<<"the error of the bind information:";
cout<<WSAGetLastError()<<endl;//输出绑定端口错误的编号,比如10048就是端口占用的意思
closesocket(server_Socket);
WSACleanup();
}else{
cout<<++produrce_Step<<"***Succee to bind the server Socket to the port"<<endl;
}
return_num = listen(server_Socket,5);//监听端口,第二个参数5表示请求队列可以容纳请求的个数
if(return_num == SOCKET_ERROR){
cout<<"There are some problem in the socket listenning"<<endl;
cout<<"The informatio of the Listen Error:"<<WSAGetLastError()<<endl;
closesocket(server_Socket);
WSACleanup();
}else{
cout<<++produrce_Step<<"The Server Socket is listenning................."<<endl;
cout<<"Please wait the client to connect!"<<endl;
}
//阻塞线程,等待客户端连接。
int actual_addr_length = sizeof(client_socket_addr);
listen_Socket = accept(server_Socket,(struct sockaddr*)&client_socket_addr,&actual_addr_length);
//记得这里要将实际的client_socket_addr的长度传入,否则accept函数可以出错,不能引起线程阻塞
if(listen_Socket == INVALID_SOCKET){
cout<<"Accpet is failed!Please check the network"<<endl;
cout<<"The Code of error information"<<WSAGetLastError()<<endl;
closesocket(listen_Socket);
WSACleanup();
}else{
cout<<++produrce_Step<<"***Client has connected with the server!"<<endl;
cout<<"The IP of the Client"<<inet_ntoa(client_socket_addr.sin_addr)<<endl;
//inet_ntoa(char*)将网络地址转换成点分十进制的形式
cout<<"The PORT of the Client"<<ntohs(client_socket_addr.sin_port)<<endl;
//ntohs (network to host short)作用是将一个16位数由网络字节顺序转换为主机字节顺序
}
char recv_Buff[1024];
char *buff = recv_Buff;
int recv_Len = 0;
/*while((recv_Len=recv(listen_Socket,buff,100,0))!=0){
if(recv_Len == SOCKET_ERROR){
cout<<"Receive the information of Client Failed"<<endl;
break;
}
buff = buff+recv_Len;
} */
recv(listen_Socket,buff,1024,0);
if(strlen(recv_Buff)>0){
cout<<"The information received is:"<<endl;
cout<<recv_Buff<<endl;
}
cout<<"Please input the saying what you want to send:";
cin>> recv_Buff;
cout<<"The information has sent to Client"<<endl;
return_num = send(listen_Socket,recv_Buff,sizeof(recv_Buff),0);
if(return_num==SOCKET_ERROR){
cout<<"Socket Send failed!"<<endl;
}
//关闭所有的套接字
closesocket(server_Socket);
closesocket(listen_Socket);
WSACleanup();
cout<<++produrce_Step<<"The Socket Qiut,BYE,BYE"<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: