1. 程式人生 > >網路通訊_UDP客戶端以及伺服器

網路通訊_UDP客戶端以及伺服器

#include<stdio.h>
#include<winsock2.h>
#include<time.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
	WSADATA wsa;
	WSAStartup(WINSOCK_VERSION,&wsa);	//初始化WS2_32.DLL

	SOCKET serversoc;
	SOCKET clientsoc;
	SOCKADDR_IN serveraddr;
	SOCKADDR_IN clientaddr;
	int client_len = sizeof(clientaddr);
	int server_len = sizeof(serveraddr);
	char *Send_data;
	int Send_len;
	char Recv_buf[64];
	int result;
	time_t nowtime;

	//命名協議,IP,埠
        serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(13);
	serveraddr.sin_addr.s_addr = INADDR_ANY;

	//建立socket
	serversoc = socket(AF_INET,SOCK_DGRAM,0);
	

	//繫結socket
	result=bind(serversoc, (SOCKADDR *)&serveraddr, server_len);
	if(result==SOCKET_ERROR)
	{
		printf("套接字繫結失敗!\n");
		closesocket(serversoc);
		return -1;
	}

	printf("Server is running.....\n");

	clientsoc = socket(AF_INET,SOCK_DGRAM,0);
	while(1)
	{   
		//接收資料
		result = recvfrom(serversoc,Recv_buf,64,0,(SOCKADDR *)&clientaddr,&client_len);
		if(result >= 0)
		{
			Recv_buf[result]= 0;
			printf("接收資料為:  %s \n",Recv_buf);
		
		    //傳送資料
			nowtime=time(0);
			Send_data=ctime(&nowtime);
			Send_len=strlen(Send_data);
	     	result = sendto(clientsoc,Send_data,Send_len,0,(SOCKADDR *)&clientaddr,sizeof(clientaddr));
			printf("Server is running.....\n");
		}
	}

	closesocket(serversoc);
	WSACleanup();
	return 0;
}