/*………………服务器端如下……………………*/(客户端另外补充)
#include
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
system("color 2");
cout<<"服务器启动.....\n";
//初始化winsock
WSADATA wsaData;
int err;
if(err=WSAStartup(MAKEWORD(2,1),&wsaData))
return 1;
if(LOBYTE(wsaData.wVersion)!=2 || HIBYTE(wsaData.wVersion)!=1)
{
WSACleanup();
return 1;
}
//创建监听套接字
SOCKET sclient=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
//绑定地址和监听套接字
sockaddr_in my_addr;//主机地址
my_addr.sin_family=AF_INET;
my_addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
my_addr.sin_port=htons(8080);//指定端口
bind(sclient,(sockaddr*)&my_addr,sizeof(my_addr));
//启动监听
if(listen(sclient,5)!=0)//10代表最大连接数
cout<<"启动监听失败!\n";
//开始接收数据
sockaddr_in c_addr;//客户地址
int addr_len=sizeof(c_addr);
SOCKET sconnect=accept(sclient,(sockaddr*)&c_addr,&addr_len);//通过监听套接字创建连接
if(sconnect==INVALID_SOCKET)//INVALID_SOCKET=-1无效的套接字
{
cout<<"invalid socket\n";
return 0;
}
cout<<"链接成功...."<
while(true)
{
char buf[1024];
char buf1[1024];
int len=recv(sconnect,buf,sizeof(buf),0);
if(len>0)
cout<<"客户说:"<
cin.getline(buf1,1024);
send(sconnect,buf1,strlen(buf1) 1,0);
/*
char kehu[1024];
string quit;
cout<<"回应(Ctrl Z to exit):";
while(cin.getline(kehu,1024))
{
send(sconnect,kehu,strlen(kehu) 1,0);
cout<<"Do you want to quit(enter -999 to quit!):";
cin>>quit;
if(strcmp(quit,"Q") == 0)
break;
}*/
}
closesocket(sclient);
WSACleanup();
system("pause");
return 0;
}