📄 server_udp.cpp
字号:
#include <stdio.h>
#include "winsock2.h"
#include "time.h"
#include "stddef.h"
#include <iostream>
using namespace std;
int main() {
//-----------------------------------------------
// Initialize Winsock
WSADATA wsaData;
SOCKET mySocket;
sockaddr_in serverAdd;
sockaddr_in clientAdd;
int Port = 27015;
char RecvBuf[5];
int BufLen=5;
WSAStartup(MAKEWORD(2,2), &wsaData);
int clientAddSize = sizeof(clientAdd);
//-----------------------------------------------
// Create a socket
mySocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(Port);
serverAdd.sin_addr.s_addr = htonl(INADDR_ANY);
//-----------------------------------------------
// Bind the socket to any address and the specified port.
int rval=bind(mySocket, (SOCKADDR *)&serverAdd, sizeof(serverAdd));
//-----------------------------------------------
//error checking
if(rval < 0)
{
cout << "binding error"<<endl;
return 0;
}
//-----------------------------------------------
// Call the recvfrom function to receive datagrams
// on the bound socket.
printf("the udp_sercer is receiving ...\n");
recvfrom(mySocket, RecvBuf, BufLen, 0,
(SOCKADDR *)&clientAdd, &clientAddSize);
//-----------------------------------------------
//Show the request of the client
printf("The client request:");
for(int i=0;i<5;i++){cout<<RecvBuf[i];}
cout<<endl;
//-----------------------------------------------
// Close the socket when finished receiving datagrams
printf("Finished receiving & Closing socket.\n");
struct tm *str;
time_t setime;
setime=time(0);
str=localtime(&setime);
printf("The sever is sending the time.\n");
sendto(mySocket,asctime(str),strlen(asctime(str))+1,0,(SOCKADDR *) &clientAdd,sizeof(clientAdd));
closesocket(mySocket);
//-----------------------------------------------
// closed
printf("the socket is closed!\n");
WSACleanup();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -