⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 recvmsg.cpp

📁 一个服务客户端通讯例子
💻 CPP
字号:
//Copyright by Yu Yanbin
//HomePage: yyb.yeah.net
//E-mail: yybhz@163.com
// RecvMsg.cpp : Defines the entry point for the application.
//

#include "stdafx.h"
#include "resource.h"
#include <winsock.h>

#define MAX_LOADSTRING 100
#define WM_MY_START WM_USER+1
#define WM_MY_THREAD WM_USER+2
#define WM_HKEY_SEND_MESSAGE WM_USER+3

// Global Variables:
HINSTANCE hInst;								// current instance
SOCKET listen_sock;
HWND hWnd;
DWORD id;
struct RevMsg{
	char ip[16];
	int port;
	char message[1024];
};
RevMsg msg;
char ip[16];
BOOL bReply=FALSE;
CRITICAL_SECTION g_cs;

// Foward declarations of functions included in this code module:
ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
BOOL StartRecvMsg(HWND hWnd);
DWORD WINAPI ListenThreadProc(LPVOID lpParameter);
LRESULT CALLBACK ShowMessage(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK SendMessageDlg(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
BOOL DoSend(char *server,char *message);
void SetReg(void);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
 	// TODO: Place code here.
	MSG msg;
	// Initialize global strings
	MyRegisterClass(hInstance);

	WSADATA wsaData;
	#define MAJOR_VERSION_REQUIRED 1
	#define MINOR_VERSION_REQUIRED 1
	
	// Prepare version for WSAStartup()
	WORD wVersionRequired = MAKEWORD(MAJOR_VERSION_REQUIRED,MINOR_VERSION_REQUIRED);
    
	// Initialize the WinSock DLL
	int nReturnCode = WSAStartup(wVersionRequired, &wsaData);
	if (nReturnCode != 0 ) 
	{
    	return 1;
	}

	if (wsaData.wVersion != wVersionRequired)
	{  	// Version needed is not available.
    	WSACleanup();
    	return 1; 
	}

	// Perform application initialization:
	if (!InitInstance (hInstance, nCmdShow)) 
		return FALSE;

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return msg.wParam;
}



//
//  FUNCTION: MyRegisterClass()
//
//  PURPOSE: Registers the window class.
//
//  COMMENTS:
//
//    This function and its usage is only necessary if you want this code
//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
//    function that was added to Windows 95. It is important to call this function
//    so that the application will get 'well formed' small icons associated
//    with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 

	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= NULL;//LoadIcon(hInstance, (LPCTSTR)IDI_RECVMSG);
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;//(LPCSTR)IDC_RECVMSG;
	wcex.lpszClassName	= "RecvMsg";
	wcex.hIconSm		=NULL;// LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);

	return RegisterClassEx(&wcex);
}

//
//   FUNCTION: InitInstance(HANDLE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	SetReg();
	InitializeCriticalSection(&g_cs);
	hInst = hInstance; // Store instance handle in our global variable
	
	hWnd = CreateWindow("RecvMsg", "RecvMsg", WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
	
	if (!hWnd)
	{
		return FALSE;
	}

	RegisterHotKey(hWnd,WM_HKEY_SEND_MESSAGE,MOD_CONTROL,VK_F5);
	
	//  ShowWindow(hWnd, SW_NORMAL);
	ShowWindow(hWnd, SW_HIDE);
	UpdateWindow(hWnd);
	SendMessage(hWnd,WM_MY_START,NULL,NULL);
	return TRUE;
}

//
//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
//  PURPOSE:  Processes messages for the main window.
//
//  WM_COMMAND	- process the application menu
//  WM_PAINT	- Paint the main window
//  WM_DESTROY	- post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId;//, wmEvent;

	switch (message) 
	{
		case WM_COMMAND:
			wmId    = LOWORD(wParam); 
			// Parse the menu selections:
			switch (wmId)
			{
				case IDM_EXIT:
				   DestroyWindow(hWnd);
				   break;
				default:
				   return DefWindowProc(hWnd, message, wParam, lParam);
			}
			break;
		case WM_MY_START:
			if(!StartRecvMsg(hWnd))PostMessage(hWnd,WM_CLOSE,NULL,NULL);
			break;
		case WM_MY_THREAD:
			EnterCriticalSection(&g_cs);
			strcpy(msg.message,((RevMsg*)lParam)->message);
			strcpy(msg.ip,((RevMsg*)lParam)->ip);
			msg.port=((RevMsg*)lParam)->port;
			strcpy(ip,msg.ip);
			LeaveCriticalSection(&g_cs);
			DialogBox(hInst, (LPCTSTR)IDD_DIALOG,NULL, (DLGPROC)ShowMessage);
			break;
		case WM_HOTKEY:
			if(wParam==WM_HKEY_SEND_MESSAGE)
			{
				DialogBox(hInst, (LPCTSTR)IDD_DIALOG1, NULL, (DLGPROC)SendMessageDlg);
			}
			break;
		case WM_DESTROY:
			WSACleanup();
			UnregisterHotKey(hWnd,WM_HKEY_SEND_MESSAGE);	
			PostQuitMessage(0);
			break;
		default:
			return DefWindowProc(hWnd, message, wParam, lParam);
   }
   return 0;
}

BOOL StartRecvMsg(HWND hWnd)
{
	listen_sock=socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
	if(listen_sock == SOCKET_ERROR)
		return FALSE;

	struct sockaddr_in addr;
	addr.sin_family=AF_INET;
	addr.sin_port=htons(3999);//Port
	addr.sin_addr.s_addr=INADDR_ANY;
	if(bind(listen_sock,(sockaddr*)&addr,sizeof(addr))==SOCKET_ERROR)
		return FALSE;

	if(listen(listen_sock,2)==SOCKET_ERROR)
		return FALSE;
	//进入Accept线程
	CreateThread(NULL, 0, ListenThreadProc, 0, 0, &id); 

	return TRUE;
}
DWORD WINAPI ListenThreadProc(LPVOID lpParameter)
{
	sockaddr_in addr;
	RevMsg msg;
	int len=sizeof(addr);
	SOCKET s=accept(listen_sock,(sockaddr*)&addr,&len);

	CreateThread(NULL, 0, ListenThreadProc, 0, 0, &id);
	if(s==SOCKET_ERROR)
		return 1;
	strcpy(msg.ip,inet_ntoa(addr.sin_addr));
	msg.port=addr.sin_port;
	
	memset(msg.message,'\0',sizeof(msg.message));
	if(recv(s,msg.message,sizeof(msg.message),0)==SOCKET_ERROR)
	{
//		wsprintf(buf,"%d%c",WSAGetLastError(),0);
//		SendMessage(hWnd,WM_MY_THREAD,NULL,(unsigned int)buf);
		return 1;
	}
	closesocket(s);
	SendMessage(hWnd,WM_MY_THREAD,NULL,(unsigned int)&msg);

	return 0;
}

LRESULT CALLBACK ShowMessage(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		char p[16];
		SetWindowText(GetDlgItem(hDlg,IDC_EDIT_IP_ADDRESS), msg.ip);
		wsprintf(p,"%d",msg.port);
		SetWindowText(GetDlgItem(hDlg,IDC_EDIT_PORT),p);
		SetWindowText(GetDlgItem(hDlg,IDC_EDIT_MESSAGE), msg.message);
		RECT rect, rect2;
		GetWindowRect(GetDesktopWindow(), &rect);
		GetClientRect(hDlg, &rect2);
		int left, right, top, bottom;
		left = rect.right / 2 - rect2.right / 2;
		top  = rect.bottom / 2 - rect2.bottom / 2;
		right = rect2.right + (GetSystemMetrics(SM_CXFRAME) * 2);
		bottom = rect2.bottom + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CXFRAME);
		SetWindowPos(hDlg,HWND_TOPMOST,left, top, right, bottom, SWP_SHOWWINDOW);
		FlashWindow(hDlg,TRUE);
		return TRUE;
		
	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK)
		{
			bReply=TRUE;
			EndDialog(hDlg, LOWORD(wParam));
			DialogBox(hInst, (LPCTSTR)IDD_DIALOG1,NULL, (DLGPROC)SendMessageDlg);
			bReply=FALSE;
			return TRUE;
		}
		if (LOWORD(wParam) == IDCANCEL) 
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
    return FALSE;
}


LRESULT CALLBACK SendMessageDlg(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		if(bReply){
			SetWindowText(GetDlgItem(hDlg,IDC_EDIT_IP),ip);
			EnableWindow(GetDlgItem(hDlg,IDC_EDIT_IP),FALSE);
		}
		RECT rect, rect2;
		GetWindowRect(GetDesktopWindow(), &rect);
		GetClientRect(hDlg, &rect2);
		int left, right, top, bottom;
		left = rect.right / 2 - rect2.right / 2;
		top  = rect.bottom / 2 - rect2.bottom / 2;
		right = rect2.right + (GetSystemMetrics(SM_CXFRAME) * 2);
		bottom = rect2.bottom + GetSystemMetrics(SM_CYCAPTION) + GetSystemMetrics(SM_CXFRAME);
		SetWindowPos(hDlg,HWND_TOPMOST,left, top, right, bottom, SWP_SHOWWINDOW);
		return TRUE;
		
	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK) 
		{
			char string[1024];
			char server[24];
			GetWindowText(GetDlgItem(hDlg,IDC_EDIT_IP), server,sizeof(server));
			GetWindowText(GetDlgItem(hDlg,IDC_EDIT_SEND_MESSAGE), string,sizeof(string));
			EndDialog(hDlg, LOWORD(wParam));
			if(!DoSend(server,string))
				MessageBox(hWnd,"发送失败!","失败",MB_OK|MB_ICONHAND);
			return TRUE;
		}

		if (LOWORD(wParam) == IDCANCEL) 
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
    return FALSE;
}
void SetReg(void)
{
	HKEY hKEY;
	LPCTSTR path="SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
	unsigned char *tmp=new unsigned char[256];

	if (RegCreateKey(HKEY_LOCAL_MACHINE, path, &hKEY) != ERROR_SUCCESS)
	{
		return; 
	}

	RegOpenKeyEx(HKEY_LOCAL_MACHINE,path,0,KEY_WRITE, &hKEY);

	char file[128];
	GetCurrentDirectory(128,file);
	if(file[strlen(file)-1]=='\\')
		strcat(file,"RecvMsg.exe");
	else
		strcat(file,"\\RecvMsg.exe");
	wsprintf((char*)tmp,"%s",file);
	RegSetValueEx(hKEY,"RecvMsg",NULL,REG_SZ,tmp,strlen((char*)tmp)+1);

	RegCloseKey(hKEY);
	delete tmp;
	return;
}

BOOL DoSend(char *server,char *message)
{
	SOCKET sock=socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
	if(sock == SOCKET_ERROR)
		return FALSE;

	hostent* h_entity;
	sockaddr_in addr;

	unsigned long ip = inet_addr(server);
	if(ip == 0xFFFFFFFF){
		h_entity = gethostbyname(server);
		if(!h_entity)
		{
			return FALSE;
		}
		memcpy(&ip, h_entity->h_addr_list[0], sizeof(int));
	}

	memcpy(&addr.sin_addr, &ip, sizeof(int));
	addr.sin_port = htons(3999);
	addr.sin_family = AF_INET;
	memset(&addr.sin_zero, 0x0, 0x08);

	if(connect(sock,(sockaddr*)&addr, sizeof(addr)))
		return FALSE;

	char buf[1024];
	fd_set readwrite_fds;

	FD_ZERO(&readwrite_fds);
	FD_SET(sock, &readwrite_fds);
	select(0,NULL,&readwrite_fds,NULL,NULL);
	memset(buf,'\0',1024);
	wsprintf(buf, "%s%c%c",message,0x0d, 0x0a);
	int nLeft=strlen(buf);
	int idx=0;
	while(nLeft>0)
	{
		int ret=send(sock,&buf[idx],strlen(buf),0);
		if(ret==SOCKET_ERROR){
			return FALSE;
		}
		nLeft-=ret;
		idx+=ret;
	}
	closesocket(sock);
	return TRUE;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -