程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 簡單的TCPIP 客戶端 服務器,tcpip客戶端服務器

簡單的TCPIP 客戶端 服務器,tcpip客戶端服務器

編輯:C++入門知識

簡單的TCPIP 客戶端 服務器,tcpip客戶端服務器


 1 // soClient.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 int _tmain(int argc, _TCHAR* argv[])
 9 {
10     WSADATA wsadata;
11     WORD dVer=MAKEWORD(2,2);
12     WSAStartup(dVer,&wsadata);
13 
14     SOCKET S=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
15     if(S==INVALID_SOCKET)
16     {
17         return FALSE;
18     }
19     sockaddr_in serverAddr;
20     serverAddr.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
21     serverAddr.sin_family=AF_INET;
22     serverAddr.sin_port=htons(4567);
23     if(::connect(S,(LPSOCKADDR)&serverAddr,sizeof(serverAddr))==SOCKET_ERROR)
24     {
25         if(WSAGetLastError()==10061)
26         {
27             printf("服務器未開啟");
28         }
29         return FALSE;
30     }
31 
32     char buff[256];
33     int irecv=::recv(S,buff,256,0);
34     if(irecv>0)
35     {
36         buff[irecv] = '\0';  //返回數據不會結束所以人工添加
37         printf("返回數據為:%s",buff);
38     }
39     
40     closesocket(S);
41     return 0;
42 }

 

 

 

 

 服務器

 1 // soServer.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 int _tmain(int argc, _TCHAR* argv[])
 9 {
10     WSADATA wsadata;
11     WORD dVer=MAKEWORD(2,2);
12     if(WSAStartup(dVer,&wsadata)!=0)
13     {
14         return FALSE;
15     }
16 
17     sockaddr_in sin;
18     sin.sin_family=AF_INET;
19     sin.sin_addr.S_un.S_addr=INADDR_ANY;
20     sin.sin_port=htons(4567);
21     SOCKET S=::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
22     
23 
24     if(::bind(S,(LPSOCKADDR)&sin,sizeof(sin))==SOCKET_ERROR)
25     {
26         return FALSE;
27     }
28 
29     if(::listen(S,2)==SOCKET_ERROR)
30     {
31         return FALSE;
32     }
33 
34     sockaddr_in remoteAddr; 
35     int nAddrLen = sizeof(remoteAddr);
36     SOCKET sClient;
37     char text[]="you have connected!welcome!";
38     printf("等待接受連接。\r\n");
39     while(TRUE)
40     {
41         sClient=::accept(S,(LPSOCKADDR)&remoteAddr,&nAddrLen);
42         if(sClient==SOCKET_ERROR)
43         {
44             printf("獲取失敗");
45             continue;
46         }
47         printf("接收到新連接:%s",inet_ntoa(remoteAddr.sin_addr));
48         send(sClient,text,strlen(text),0);
49         closesocket(sClient);
50     }
51     closesocket(S);
52     return 0;
53 }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved