• 基于UDP Socket例子


    客户端程序代码如下:

    #pragma comment(lib,"ws2_32.lib")
    #include<winsock2.h>
    #include<stdio.h>
    BOOL InitWinsock();
    void main()
    {
    	SOCKET socket1;
    	InitWinsock();
    	struct sockaddr_in server;
    	int len=sizeof(server);
    	server.sin_family=AF_INET;
    	server.sin_port=htons(1000);	//Server的监听端口为1000
    	server.sin_addr.s_addr=inet_addr("192.168.0.199");
    	socket1=socket(AF_INET,SOCK_DGRAM,0);
    	while(1)
    	{
    		char buffer[1024]="\0";
    		printf("input message\n");
    		scanf("%s",buffer);
    		if(strcmp(buffer,"bye")==0)
    			break;
    		if(sendto(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&server,len)!=SOCKET_ERROR)
    		{
    			if(recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr *)&server,&len)!=SOCKET_ERROR)
    				printf("rece from server:%s\n",buffer);
    		}
    	}
    	closesocket(socket1);
    }
    
    BOOL InitWinsock()
    {
    	int Error;
    	WORD VersionRequested;
    	WSADATA WsaData;
    	VersionRequested=MAKEWORD(2,2);
    	Error=WSAStartup(VersionRequested,&WsaData);
    	if(Error!=0)
    	{
    		return FALSE;
    	}
    	else
    	{
    		if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2)
    		{
    			WSACleanup();
    			return FALSE;
    		}
    	}
    	return TRUE;
    }
    

     //htons()的功能:将一个无符号短整型数值转换为网络字节序,即大端模式(big-endian)

    服务端程序代码:

    #pragma comment(lib,"ws2_32.lib")
    #include<winsock2.h>
    #include<stdio.h>
    BOOL InitWinsock();
    void main()
    {
    	SOCKET socket1;
    	InitWinsock();
    	struct sockaddr_in local;
    	struct sockaddr_in from;
    	int fromlen=sizeof(from);
    	local.sin_family=AF_INET;
    	local.sin_port=htons(1000);  //监听端口
    	local.sin_addr.s_addr=INADDR_ANY;  //本机
    	socket1=socket(AF_INET,SOCK_DGRAM,0);
    	bind(socket1,(struct sockaddr*)&local,sizeof(local));
    	while(1)
    	{
    		char buffer[1024]="\0";
    		printf("waiting for message from others-------------");
    		if(recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&from,&fromlen)!=SOCKET_ERROR)
    		{
    			printf("Received datagram from %s--%s\n",inet_ntoa(from.sin_addr),buffer);
                  //给Client发信息 sendto(socket1,strcat(buffer,"hello"),sizeof(strcat(buffer,"hello")),0,(struct sockaddr*)&from,fromlen); printf("%s",buffer); } Sleep(500); } closesocket(socket1); } BOOL InitWinsock() { int Error; WORD VersionRequested; WSADATA WsaData; VersionRequested=MAKEWORD(2,2); Error=WSAStartup(VersionRequested,&WsaData); if(Error!=0) { return FALSE; } else { if(LOBYTE(WsaData.wVersion)!=2||HIBYTE(WsaData.wHighVersion)!=2) { WSACleanup(); return FALSE; } } return TRUE; }
  • 相关阅读:
    open-falcon之agent
    centos 7 部署 open-falcon 0.2.0
    高可用Redis服务架构分析与搭建
    python操作mongo脚本
    mongo查询日期格式数据
    离线下载pip包安装
    mongo同步到es
    mongo ttl索引
    kibana多台服务部署
    logstash过滤配置
  • 原文地址:https://www.cnblogs.com/shanmao/p/2779556.html
Copyright © 2020-2023  润新知