Socket 开关显示器

局域网内手机控制开关工作电脑显示器:

#include <winsock2.h>
#include <stdio.h>
#include <windows.h>
#pragma comment(lib,"ws2_32.lib")

int main(int argc, char* argv[]){
	short port=8000;
    WSADATA wsa;
init:
    //init socket
    if(WSAStartup(MAKEWORD(2,2),&wsa)!=0){
        printf("init failed\n");
        exit(-1);
    }
    //create sockt
    SOCKET serverSocket;
    if((serverSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==INVALID_SOCKET){
        printf("create failed\n");
        exit(-1);
    }
    struct sockaddr_in serverAddress;
    memset(&serverAddress,0,sizeof(sockaddr_in));
    serverAddress.sin_family=AF_INET;
    serverAddress.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
    serverAddress.sin_port = htons(port);
    if(bind(serverSocket,(sockaddr*)&serverAddress,sizeof(serverAddress))==SOCKET_ERROR){
        printf("port: %d\n",port);
        exit(-1);
    }
    if(listen(serverSocket,SOMAXCONN)==SOCKET_ERROR){
        printf("listen failed\n");
        exit(-1);
    }
    printf("Server %d is listening......\n",port);
    SOCKET clientSocket;
    struct sockaddr_in clientAddress;//address
    memset(&clientAddress,0,sizeof(clientAddress));
    int addrlen = sizeof(clientAddress);
    //accept connection
    if((clientSocket=accept(serverSocket,(sockaddr*)&clientAddress,&addrlen))==INVALID_SOCKET){
        printf("connect failed");
        exit(-1);
    }
    printf("Accept connection from %s\n",inet_ntoa(clientAddress.sin_addr));
    char buf[4096];
    while(1){
        //receive data
        int bytes;
        if((bytes=recv(clientSocket,buf,sizeof(buf),0))==0){
            printf("receive faild\n");
			WSACleanup();
			goto init;
        }
        buf[bytes]='\0';
        printf("Message from %s %s\n",inet_ntoa(clientAddress.sin_addr),buf);
		if(buf[0]=='a')
		{
			SendMessage(HWND_BROADCAST,WM_SYSCOMMAND,SC_MONITORPOWER,2);//close monitor
		}
		if(buf[0]=='b')
		{
			SendMessage(HWND_BROADCAST,WM_SYSCOMMAND,SC_MONITORPOWER,-1);//open monitor
		}
        if(send(clientSocket,buf,bytes,0)==SOCKET_ERROR){
            printf("send faild\n");
            WSACleanup();
			goto init;
        }
    }
    WSACleanup();
    return 0;
}

Socket 开关显示器_第1张图片

你可能感兴趣的:(c,android,开关,显示器)