今天终于搞定个最简单的网络C/s编程了

类别:编程语言 点击:0 评论:0 推荐:

服务端

#include<winsock2.h>
#include<stdio.h>
#include<windows.h>
#pragma comment(lib,"WS2_32.lib")

int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,0);
WSAStartup(sockVersion,&wsaData);

SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
  printf(" Failed socket()\n");
  WSACleanup();
  return 0;
}

sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(8888);
sin.sin_addr.S_un.S_addr=INADDR_ANY;

if(bind(s,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
{
  printf(" Failed bind()\n");
  WSACleanup();
  return 0;
}

if(listen(s,2)==SOCKET_ERROR)
{
  printf(" Failed listen()\n");
  WSACleanup();
  return 0;
}


sockaddr_in remoteAddr;
int nAddrLen=sizeof(remoteAddr);
SOCKET client;
char szText[]="Hello World!";


while(TRUE)
{
 client=accept(s,(SOCKADDR*)&remoteAddr,&nAddrLen);
 if(client==INVALID_SOCKET)
  {
          printf(" Failed accept()\n");
          continue;
  }
 printf("接收到一个连接:%s\n",inet_ntoa(remoteAddr.sin_addr));
 send(client,szText,strlen(szText),0);
 closesocket(client);
}

closesocket(s);
WSACleanup();
return 0;

}

客户端

#include<winsock2.h>
#include<stdio.h>
#include<windows.h>
#pragma comment(lib,"WS2_32.lib")

int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD sockVersion=MAKEWORD(2,0);
WSAStartup(sockVersion,&wsaData);

SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s==INVALID_SOCKET)
{
  printf(" Failed socket()\n");
  WSACleanup();
  return 0;
}

sockaddr_in servAddr;
servAddr.sin_family=AF_INET;
servAddr.sin_port=htons(8888);
servAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");


if(connect(s,(sockaddr*)&servAddr,sizeof(servAddr))==-1)
{
  printf(" Failed connect()\n");
  WSACleanup();
  return 0;
}

char buffer[256];
int nRecv=recv(s,buffer,256,0);
if(nRecv>0)
{
 buffer[nRecv]='\0';
 printf("已经接收到数据:%s\n",buffer);
}
closesocket(s);
WSACleanup();
return 0;

}


本文地址:http://com.8s8s.com/it/it22550.htm