windows下簡單的C語言伺服器(TCP)
阿新 • • 發佈:2019-02-01
回顧下windows下網路方面的東西 首先寫了下C語言的socket
--檢視本機IP:ipconfig/all
---C語言實現
---visual studio 2012
Server:
#include <stdio.h> #include <winsock2.h> #pragma comment(lib,"ws2_32.lib") int main(void) { //初始化wsa WORD sockVision = MAKEWORD(2,2); WSADATA wsadata; //其他變數 SOCKET slisten; SOCKET sClient; struct sockaddr_in remoteAddr; struct sockaddr_in sin; int ret = -1; int nAddrlen = sizeof(remoteAddr); char revdata[255]; char senddata[255]; if( WSAStartup(sockVision,&wsadata) != 0 ) { printf("WSA初始化失敗\n"); return 0; } //建立套接字 slisten = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(slisten == INVALID_SOCKET) { printf("socket監聽者建立失敗\n"); return 0; } //繫結IP和埠 sin.sin_family = AF_INET; sin.sin_port = htons(8888); sin.sin_addr.S_un.S_addr = INADDR_ANY; if( bind(slisten,(LPSOCKADDR)&sin,sizeof(sin)) == SOCKET_ERROR ) { printf("繫結IP和埠\n"); return 0; } //監聽 if(listen(slisten,5) == SOCKET_ERROR) { printf("監聽失敗\n"); return 0; } //迴圈接收資料 while(1) { printf("等待連線.........\n"); sClient = accept(slisten,(SOCKADDR *)&remoteAddr,&nAddrlen); if(sClient == INVALID_SOCKET) { printf("接受客戶端失敗,正在重試.........\n"); continue; } printf("接受客戶端成功:%s\n",inet_ntoa(remoteAddr.sin_addr)); //接收資料 while(1) { ret = recv(sClient,revdata,255,0); if(ret > 0) { revdata[ret] = 0x00; printf("\n"); printf("客戶:"); printf(revdata); printf("\n"); } if(strcmp(revdata,"bye") == 0) break; //傳送資料 printf("我:"); scanf("%s",senddata); send(sClient,senddata,strlen(senddata),0); } closesocket(sClient); } closesocket(sClient); WSACleanup(); return 0; }
Client:
#include <stdio.h> #include <winsock2.h> #pragma comment(lib,"ws2_32.lib") int main(void) { WORD sockVision = MAKEWORD(2,2); WSADATA wsadata; SOCKET sclient ; struct sockaddr_in serAddr; char senddata[255]; char revdata[255]; int ret = -1; if(WSAStartup(sockVision,&wsadata) != 0) { printf("WSA初始化失敗\n"); return 0; } sclient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(sclient == INVALID_SOCKET) { printf("socket客戶端建立失敗\n"); return 0; } serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); serAddr.sin_addr.S_un.S_addr = inet_addr("192.168.1.224"); if( connect(sclient,(SOCKADDR *)&serAddr,sizeof(serAddr)) == SOCKET_ERROR ) { printf("socket客戶端連線失敗\n"); return 0; } while(1) { printf("我:"); scanf("%s",senddata); send(sclient,senddata,strlen(senddata),0); if(strcmp(senddata,"bye") == 0) break; ret = recv(sclient,revdata,255,0); if(ret > 0) { revdata[ret] = 0x00; printf("\n"); printf("伺服器:"); printf(revdata); printf("\n"); } } closesocket(sclient); WSACleanup(); system("pause"); return 0; }