Windows下C語言的Socket程式設計例子(TCP和UDP)
阿新 • • 發佈:2019-02-12
1 #include "stdafx.h" 2 #include <stdio.h> 3 #include <winsock2.h> 4 5 #pragma comment(lib,"ws2_32.lib") 6 7 int main(int argc, char* argv[]) 8 { 9 //初始化WSA 10 WORD sockVersion = MAKEWORD(2,2); 11 WSADATA wsaData; 12 if(WSAStartup(sockVersion, &wsaData)!=0) 13{ 14 return 0; 15 } 16 17 //建立套接字 18 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 19 if(slisten == INVALID_SOCKET) 20 { 21 printf("socket error !"); 22 return 0; 23 } 24 25 //繫結IP和埠 26 sockaddr_in sin; 27 sin.sin_family = AF_INET;28 sin.sin_port = htons(8888); 29 sin.sin_addr.S_un.S_addr = INADDR_ANY; 30 if(bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) 31 { 32 printf("bind error !"); 33 } 34 35 //開始監聽 36 if(listen(slisten, 5) == SOCKET_ERROR) 37 { 38 printf("listen error !"); 39 return 0; 40 } 41 42 //迴圈接收資料 43 SOCKET sClient; 44 sockaddr_in remoteAddr; 45 int nAddrlen = sizeof(remoteAddr); 46 char revData[255]; 47 while (true) 48 { 49 printf("等待連線...\n"); 50 sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); 51 if(sClient == INVALID_SOCKET) 52 { 53 printf("accept error !"); 54 continue; 55 } 56 printf("接受到一個連線:%s \r\n", inet_ntoa(remoteAddr.sin_addr)); 57 58 //接收資料 59 int ret = recv(sClient, revData, 255, 0); 60 if(ret > 0) 61 { 62 revData[ret] = 0x00; 63 printf(revData); 64 } 65 66 //傳送資料 67 char * sendData = "你好,TCP客戶端!\n"; 68 send(sClient, sendData, strlen(sendData), 0); 69 closesocket(sClient); 70 } 71 72 closesocket(slisten); 73 WSACleanup(); 74 return 0; 75 }