一个最简单聊天程序

来源:互联网 发布:外国域名注册 编辑:程序博客网 时间:2024/06/06 14:12
//客户端的代码:
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <conio.h>
  4. #include <winsock2.h>
  5. #pragma comment(lib, "Ws2_32.lib")
  6. SOCKET self;
  7. long chang;
  8. sockaddr_in local1;
  9. WSADATA data;
  10. int dataReturn;
  11. bool canrecv = true;
  12. char chat1[256] = {0};
  13. static char addrto[50] = {0};
  14. char recevie1[256] = {0};
  15. int MyClient(void)
  16. {
  17.     dataReturn = WSAStartup(0x101,&data);
  18.     if(dataReturn)
  19.     {
  20.         printf("未知错误!/n");
  21.         WSACleanup();
  22.         return 0;
  23.     }
  24.     self = socket(AF_INET,SOCK_STREAM,0);
  25.     if(self == INVALID_SOCKET)
  26.     {
  27.         printf("创建socket失败!/n");
  28.         return 0;
  29.     }
  30.     local1.sin_family = AF_INET;
  31.     local1.sin_port = htons((u_short)4567);
  32.     while(1)
  33.     {
  34.         printf("请输入你要登陆的IP地址:");
  35.         scanf("%s",addrto);
  36.         local1.sin_addr.s_addr = inet_addr(addrto);
  37.         printf("正在登陆…………/n");
  38.         chang = connect(self,(sockaddr *)&local1,sizeof(local1));
  39.         if(chang == -1)
  40.         {
  41.             printf("connect失败!/n");
  42.             WSACleanup();
  43.             return 0;
  44.         }
  45.         while(1)
  46.         {
  47.             if(canrecv)
  48.             {
  49.                 printf("………………………………………接收消息……………………………………/n");
  50.                 recv(self,recevie1,sizeof(recevie1),0);
  51.                 printf("%s/n",recevie1);
  52.                 canrecv = false;
  53.                 printf("………………………………………接收完成……………………………………/n");
  54.             }
  55.             else
  56.             {
  57.                 printf("请输入你要说的话:");
  58.                 scanf("%s/0",chat1);
  59.                 send(self,chat1,sizeof(chat1),0);
  60.                 canrecv = true;
  61.             }
  62.         }
  63.         
  64.     }
  65.     closesocket(self);
  66.     WSACleanup();
  67.     return 0;
  68. }
  69. int main(void)
  70. {
  71.     int yes;
  72.     yes = MyClient();
  73.     if(!yes)
  74.     {
  75.         printf("启动客户端失败!/n");
  76.     }
  77.     
  78.     return 0;
  79. }
原创粉丝点击