
#pragma comment(lib,"ws2_32.lib")//第二版本32位的把lib檔案添加到專案中windows套接字的元件
#include<stdio.h>
#include<stdlib.h>
#include<WinSock2.h>
void main(void)
{
WSADATA wsaData; //定義一個data,data用來初始化windows套接字socket(***---這是第一步---***)
SOCKET ListeningSocket; //定義一個套接字
SOCKET NewConnection; //定義一個客戶端套接字
SOCKADDR_IN ServerAddr; //創建服務端地址
SOCKADDR_IN ClientAddr; //創建客戶端地址
int ClientAddrLen; //宣告客戶端地址長度
int Ret; //檢查初始化是否成功,接受了多少個位元組
int Port=5150;
char DataBuffer[1024];
if((Ret=WSAStartup(MAKEWORD(2,2),&wsaData))!=0)
{
printf("WSAStartup failed with error %d\n",Ret);//初始化失敗回傳錯誤資訊
system("pause");
return;
}
if((ListeningSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)==INVALID_SOCKET)) //使用if判斷是否創建成功
{
printf("socket failed with error %d\n",WSAGetLastError);//使用WSAGetLastError得到錯誤資訊
WSACleanup();//結束前清理
system("pause");
return;
}
ServerAddr.sin_family=AF_INET;
ServerAddr.sin_port=htons(Port);
ServerAddr.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
if((bind(ListeningSocket,(SOCKADDR*)&ServerAddr,sizeof(ServerAddr)))==SOCKET_ERROR)
{
printf("bind failed with error %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
if((listen(ListeningSocket,5))==SOCKET_ERROR)
{
printf("listen failed with error %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
printf("We are waiting a connection on port %d.\n",Port);
printf("Listen(正在監聽)...\n");
if((NewConnection=accept(ListeningSocket,(SOCKADDR*)&ClientAddr,&ClientAddrLen))==INVALID_SOCKET)
//在此定義一個客戶端的套接字,接收后會得到一個客戶端的套接字
{
printf("ACCEPT FAILED WITH ERROR %d\n",WSAGetLastError());
closesocket(ListeningSocket);
WSACleanup();
system("pause");
return;
}
printf("We successfully got a connectiong from %s:%d\n",inet_ntoa(ClientAddr.sin_addr),ntohs(ClientAddr.sin_port));
if((Ret =recv(NewConnection,DataBuffer,sizeof(DataBuffer),0))==SOCKET_ERROR)
{
printf("recv failed with error %d\n",WSAGetLastError());
closesocket(NewConnection);
WSACleanup();
system("pause");
return;
}
//此時已成功接收到客戶端發送來的資料,將其顯示出來
printf("We successfully received %d bytes.\n",Ret);
DataBuffer[Ret]='\0';//結尾加上\0表示字串結束
printf("%s\n",DataBuffer);
printf("Ww are now going to close the client connectiong.\n");
closesocket(NewConnection);
WSACleanup();
system("pause");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/134168.html
標籤:網絡通信
上一篇:路由器控制訪問特定的網站
下一篇:服務器ping ip時斷時續
