- //client
- #include <iostream>
- #include <locale>
- #include <WINSOCK2.H>
- #include <Windows.h>
- #include <WinUser.h>
- #include <cstdio>
- #define SERVER_ADDRESS "12.12.12.67" //服务器端IP地址
- #define PORT 6000
- #define MSGSIZE 1024
- #pragma comment(lib, "ws2_32.lib")
- using namespace std;
- wstring getcomputername();
- void locksystem();
- DWORD WINAPI FunThread(LPVOID);
- SOCKET sClient;
- SOCKADDR_IN server;
- int main()
- {
- WSADATA wsaData;
- char c_Message[MSGSIZE];
- WSAStartup(0x0202, &wsaData);
- sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
- memset(&server, 0, sizeof(SOCKADDR_IN)); //先将保存地址的server置为全0
- server.sin_family = PF_INET; //声明地址格式是TCP/IP地址格式
- server.sin_port = htons(PORT); //指明连接服务器的端口号
- server.sin_addr.s_addr = inet_addr(SERVER_ADDRESS); //指明连接服务器的IP地址
- connect(sClient, (struct sockaddr *)&server, sizeof(SOCKADDR_IN));
- //连到刚才指明的服务器上
- HANDLE hThread=CreateThread(NULL,0,FunThread,0,0,0); // Create a new thread to Recv()
- WaitForSingleObject(hThread, INFINITE);
- CloseHandle(hThread);
- /*
- while (TRUE)
- {
- printf("Client Send:");
- gets(c_Message);
- send(sClient, c_Message, strlen(c_Message), 0);
- if(!strcmp(c_Message,"exit"))//client自身退出
- exit(1);
- }
- */
- // 释放连接和进行结束工作
- closesocket(sClient);
- WSACleanup();
- return 0;
- }
- DWORD WINAPI FunThread(LPVOID)
- {
- char s_Message[MSGSIZE];
- int ret;
- while (TRUE)
- {
- ret = recv(sClient, s_Message, MSGSIZE, 0); //Recv()
- if(ret==SOCKET_ERROR)
- {
- printf("\nServer is closed!\n");
- exit(1);
- }
- s_Message[ret] = '\0';
- printf("\nReceived: %s\n", s_Message);
- //分支结构
- if(strcmp(s_Message,"exit") == 0)//server让client退出
- {
- exit(1);
- }
- else if(strcmp(s_Message,"name") == 0)
- {
- wstring name = getcomputername();
- wcout<<name<<endl;
- char *c_Message = new char[MSGSIZE];
- sprintf(c_Message, "%ls", name.c_str()); //Wstring类型to char[]类型
- send(sClient, c_Message, strlen(c_Message), 0);
- }
- else if(strcmp(s_Message,"lock") == 0)
- {
- locksystem();
- char *c_Message = "Locked.\n";
- send(sClient, c_Message, strlen(c_Message), 0);
- }
- else if(strncmp(s_Message, "execute", 7) == 0) //尽比较前7个字符
- {
- char *c_Message = new char[MSGSIZE];
- strcpy(c_Message, s_Message+8); //取出后面的参数
- cout<<c_Message<<endl;
- ShellExecuteA(NULL,"open",c_Message,NULL,NULL,SW_HIDE);
- }
- }
- return 0;
- }
- wstring getcomputername()
- {
- DWORD size = 0;
- wstring wstr;
- GetComputerNameW(NULL,&size);
- wchar_t *name = new wchar_t[size];
- if(GetComputerNameW(name, &size))
- wstr = name;
- delete[] name;
- return wstr;
- }
- void locksystem()
- {
- LockWorkStation();
- }
WinSocket的最简单示例
最新推荐文章于 2019-10-16 11:54:01 发布