C++中socket编程

原文:http://blog.csdn.net/cuiran/article/details/5854794

Server端

 1 #include <WINSOCK2.H>
 2 #include <stdio.h>
 3 #pragma comment(lib,"ws2_32.lib")
 4 void main()
 5 {
 6  //创建套接字
 7  WORD myVersionRequest;
 8  WSADATA wsaData;
 9  myVersionRequest=MAKEWORD(1,1);
10  int err;
11  err=WSAStartup(myVersionRequest,&wsaData);
12  if (!err)
13  {
14   printf("已打开套接字/n");
15 
16  } 
17  else
18  {
19   //进一步绑定套接字
20   printf("嵌套字未打开!");
21   return;
22  }
23  SOCKET serSocket=socket(AF_INET,SOCK_STREAM,0);//创建了可识别套接字
24  //需要绑定的参数
25  SOCKADDR_IN addr;
26  addr.sin_family=AF_INET;
27  addr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);//ip地址
28  addr.sin_port=htons(6000);//绑定端口
29  
30  bind(serSocket,(SOCKADDR*)&addr,sizeof(SOCKADDR));//绑定完成
31  listen(serSocket,5);//其中第二个参数代表能够接收的最多的连接数
32  
33  //////////////////////////////////////////////////////////////////////////
34  //开始进行监听
35  //////////////////////////////////////////////////////////////////////////
36  SOCKADDR_IN clientsocket;
37  int len=sizeof(SOCKADDR);
38  while (1)
39  {
40   SOCKET serConn=accept(serSocket,(SOCKADDR*)&clientsocket,&len);//如果这里不是accept而是conection的话。。就会不断的监听
41   char sendBuf[100];
42   
43   sprintf(sendBuf,"welcome %s to bejing",inet_ntoa(clientsocket.sin_addr));//找对对应的IP并且将这行字打印到那里
44   send(serConn,sendBuf,strlen(sendBuf)+1,0);
45   char receiveBuf[100];//接收
46   recv(serConn,receiveBuf,strlen(receiveBuf)+1,0);
47   printf("%s/n",receiveBuf);
48   closesocket(serConn);//关闭
49  WSACleanup();//释放资源的操作
50  }
51 }

Client端

 1 #include <WINSOCK2.H>
 2 #include <stdio.h>
 3 #pragma comment(lib,"ws2_32.lib")
 4 
 5 void main()
 6 {
 7  int err;
 8  WORD versionRequired;
 9  WSADATA wsaData;
10  versionRequired=MAKEWORD(1,1);
11  err=WSAStartup(versionRequired,&wsaData);//协议库的版本信息
12 
13  if (!err)
14  {
15   printf("客户端嵌套字已经打开!/n");
16  }
17  else
18  {
19   printf("客户端的嵌套字打开失败!/n");
20   return;//结束
21  }
22  SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);
23  SOCKADDR_IN clientsock_in;
24  clientsock_in.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
25  clientsock_in.sin_family=AF_INET;
26  clientsock_in.sin_port=htons(6000);
27  //bind(clientSocket,(SOCKADDR*)&clientsock_in,strlen(SOCKADDR));//注意第三个参数
28  //listen(clientSocket,5);
29  connect(clientSocket,(SOCKADDR*)&clientsock_in,sizeof(SOCKADDR));//开始连接
30 
31  char receiveBuf[100];
32  recv(clientSocket,receiveBuf,101,0);
33  printf("%s/n",receiveBuf);
34 
35  send(clientSocket,"hello,this is client",strlen("hello,this is client")+1,0);
36  closesocket(clientSocket);
37  WSACleanup();
38 }

 

posted @ 2014-01-13 15:52  erictanghu  阅读(270)  评论(0编辑  收藏  举报