C++ 简单的 Tcp 实现 socket 客户端与客户端通信

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.youkuaiyun.com/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

开发环境  Vs 2008  新建一个 win32 console  project

 

//  服务器端代码


  1. // Server.cpp : Defines the entry point for the console application.  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5. #include "winsock2.h"  
  6. #pragma comment(lib, "ws2_32.lib")  
  7.   
  8. #include <iostream>  
  9. using namespace std;  
  10.   
  11. int _tmain(int argc, char* argv[])  
  12. {  
  13.     const int BUF_SIZE = 64;  
  14.   
  15.     WSADATA         wsd;            //WSADATA变量  
  16.     SOCKET          sServer;        //服务器套接字  
  17.     SOCKET          sClient;        //客户端套接字  
  18.     SOCKADDR_IN     addrServ;;      //服务器地址  
  19.     char            buf[BUF_SIZE];  //接收数据缓冲区  
  20.     char            sendBuf[BUF_SIZE];//返回给客户端得数据  
  21.     int             retVal;         //返回值  
  22.   
  23.     //初始化套结字动态库  
  24.     if (WSAStartup(MAKEWORD(2,2), &wsd) != 0)  
  25.     {  
  26.         cout << "WSAStartup failed!" << endl;  
  27.         return 1;  
  28.     }  
  29.       
  30.     //创建套接字  
  31.     sServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);      
  32.     if(INVALID_SOCKET == sServer)  
  33.     {  
  34.         cout << "socket failed!" << endl;  
  35.         WSACleanup();//释放套接字资源;  
  36.         return  -1;  
  37.     }  
  38.       
  39.     //服务器套接字地址   
  40.     addrServ.sin_family = AF_INET;  
  41.     addrServ.sin_port = htons(4999);  
  42.     addrServ.sin_addr.s_addr = INADDR_ANY;        
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值