我在VS2012中写了一个简单的C / S项目。但它不起作用。
服务器代码:
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#include <iostream>
#include <string>
using namespace std;
#define BU_SIZ 64
int main(){
WSADATA wd;
SOCKET s;
if(WSAStartup(MAKEWORD(2,2),&wd) != 0){
cout<<"er stup";
return 0;
}
cout<<"V:"<<wd.wVersion<<endl;
cout<<"H V:"<<wd.wHighVersion<<endl;
cout<<"Dsp:"<<wd.szDescription<<endl;
cout<<"Sys:"<<wd.szSystemStatus<<endl;
s = socket(AF_INET,SOCK_STREAM,0);
if(s == INVALID_SOCKET){
cout<<"failed in socket"<<endl;
WSACleanup();
return -1;
}
SOCKADDR_IN sa;
sa.sin_family = AF_INET;
sa.sin_port = htons(33333);
sa.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
int ret;
ret = bind(s,(const struct sockaddr*)&sa,sizeof(SOCKADDR_IN));
if(ret == SOCKET_ERROR){
cout<<"failed in bind"<<endl;
WSACleanup();
return -1;
}
ret = listen(s,2);
if(ret == SOCKET_ERROR){
cout<<"failed in listen"<<endl;
WSACleanup();
return -1;
}
cout<<"server start"<<endl;
sockaddr_in ca;
int ca_len = sizeof(ca);
SOCKET c;
c = accept(s,(sockaddr FAR*)&ca,&ca_len);
int r = WSAGetLastError();
if(c = SOCKET_ERROR){
cout<<"failed in accept"<<endl;
cout<<r<<endl<<endl;
closesocket(s);
WSACleanup();
return -1;
}
char buf[BU_SIZ];
while(1){
ZeroMemory(buf,BU_SIZ);
ret = recv(c,buf,BU_SIZ,0);
if(ret == SOCKET_ERROR){
cout<<"failed in listen"<<endl;
closesocket(s);
closesocket(c);
WSACleanup();
return -1;
}
if(strcmp(buf,"quit") == 0){
ret = send(c,"quit",sizeof("quit"),0);
break;
}
else{
cout<<"msg is:"<<buf<<endl;
}
closesocket(s);
closesocket(c);
WSACleanup();
}
return 0;
}
客户代码:
#include <iostream>
#include <string>
#include <WinSock2.h>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
#define BUF_SIZ 64
int main(){
SOCKET c;
WSADATA wd;
char buf[BUF_SIZ] = {0};
WSAStartup(MAKEWORD(2,2),&wd);
c = socket(AF_INET,SOCK_STREAM,0);
SOCKADDR_IN ca;
ca.sin_family = AF_INET;
ca.sin_port = htons(33333);
ca.sin_addr.S_un.S_addr = inet_addr("192.168.199.232");
int ret;
ret = connect(c,(LPSOCKADDR)&ca,sizeof(ca));
if(ret == SOCKET_ERROR){
cout<<"fail at conn"<<endl;
closesocket(c);
WSACleanup();
return -1;
}
cout<<"after conn"<<endl;
while(1){
string st;
cin>>st;
int i = 0;
do{
buf[i] = st[i];
}while(st[i] != 0);
ret = send(c,buf,strlen(buf)+1,0);
if(ret == SOCKET_ERROR){
cout<<"fail at send"<<endl;
closesocket(c);
WSACleanup();
return -1;
}
recv(c,buf,sizeof(buf),0);
if(strcmp(buf,"quit") == 0){
break;
}
}
closesocket(c);
WSACleanup();
return 0;
}
运行后,服务器显示enter image description here Aftre客户端运行:enter image description here
客户端显示“在conn之后”,但它不会终止。
答案 0 :(得分:0)
只是因为我失去了一个相等的... if(==)但我写了if(=)