socket udp

//Server 端程序源代码: 
#include <stdio.h> 
#include <Winsock2.h>
#pragma comment (lib, "ws2_32")  
#include <thread>  

struct sockaddr_in from; 
int fromlen =sizeof(from); 
void recvFunction(SOCKET& sockClient)  
{  
	while (true)  
	{  
		char buffer[1024]="\0"; 
		printf("waiting for message from others-------------\n"); 
		if (recvfrom(sockClient,buffer,sizeof(buffer),0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR) 
		{ 
			printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer); 
			////给cilent发信息 
			sendto(sockClient,buffer,sizeof(buffer),0,(struct sockaddr*)&from,fromlen); 
		} 

	}  

}
void sendFuction(SOCKET &sockConn)  
{  
	while (true)  
	{  
	}  

} 

void main() 
{ 
	SOCKET socket1; 
	//InitWinsock(); 
	WSADATA wsaData; 
	int iErrorCode; 
	if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL 
	{ 
		printf("Winsock无法初始化!\n"); 
		WSACleanup(); 
		return; 
	} 
	printf("服务器开始创建SOCKET。\n"); 
	struct sockaddr_in local; 
	local.sin_family=AF_INET; 
	local.sin_port=htons(27015); ///监听端口 
	local.sin_addr.s_addr=INADDR_ANY; ///本机 
	socket1=socket(AF_INET,SOCK_DGRAM,0); 
	bind(socket1,(struct sockaddr*)&local,sizeof(local)); 

	std::thread recvThread(recvFunction,socket1);  
	recvThread.detach();  

	std::thread sendThread(sendFuction,socket1);  
	sendThread.detach(); 

	while (1) 
	{ 
	} 
	closesocket(socket1);
	WSACleanup();    
} 

//Client端源代码: 
#include <stdio.h> 
#include <Winsock2.h> 
#pragma comment (lib, "ws2_32")  
#include <thread>  
struct sockaddr_in server;
int len =sizeof(server); 
void recvFunction(SOCKET& sockClient)  
{  
	while (true)  
	{  
		char recvBuf[50];  
		if(recvfrom(sockClient,recvBuf,50,0,(struct sockaddr*)&server,&len) != SOCKET_ERROR)
		{
			printf("rece from server:%s\n",recvBuf); 
		}
		
	}  

}
void sendFuction(SOCKET &sockConn)  
{  
	while (true)  
	{  
		char buffer[1024]="\0"; 
		printf("input message\n"); 
		scanf("%s",buffer); 
		//     printf("%s",buffer); 
		if (strcmp(buffer,"bye")==0) 
		{ 
			printf("退出!\n"); 
			Sleep(100); 
			closesocket(sockConn); 
			break; 
		} 
		if (sendto(sockConn,buffer,sizeof(buffer),0,(struct sockaddr*)&server,len)!=SOCKET_ERROR) 
		{ 
			
		} 
	}  

} 
void main() 
{ 
	SOCKET socket1; 
	//InitWinsock(); 
	WSADATA wsaData; 
	int iErrorCode; 
	if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL 
	{ 
		printf("Winsock无法初始化!\n"); 
		WSACleanup(); 
		return; 
	} 
	printf("服务器开始创建SOCKET。\n"); 
	 
	
	server.sin_family=AF_INET; 
	server.sin_port=htons(27015); ///server的监听端口 
	server.sin_addr.s_addr=inet_addr("192.168.0.148"); ///server的地址 
	socket1=socket(AF_INET,SOCK_DGRAM,0); 

	//多线程  
	std::thread recvThread(recvFunction,socket1);  
	recvThread.detach();  

	std::thread sendThread(sendFuction,socket1);  
	sendThread.detach();  

	while (1) 
	{ 
		
	} 
	closesocket(socket1);
	WSACleanup();   

}

你可能感兴趣的:(socket udp)