Click here to Skip to main content
15,886,422 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
is there any way to make this code.. err... more slimline and more efficient?

#include <winsock2.h>
#include <windows.h>
#include "resource.h"

#define WIN32_LEAN_AND_MEAN

#define WM_SOCKET		100
#define IDC_EDIT_OUT	101
#define IDC_EDIT_IN		102
#define IDC_ListBox		2000

void vShowText(HWND	hChildHandle, char *szText);

char szServer[15] = "127.0.0.1";

//arrays to hold data
char RecvData[100];
char SendData[100] = "REQ";

int SendBytes = 0;
int RecvBytes = 0;

int nResult = 0;
int iResult = 0;

char buffer[100];
char error[100];

SOCKADDR_IN SockAddr;

SOCKET Socket = NULL;

HWND hlistbox = NULL;
HWND hEditOut = NULL;
HWND hEditIn = NULL;

LRESULT CALLBACK WinProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	HDC hdc;
	PAINTSTRUCT ps;

	switch(uMsg)
	{
	case WM_CREATE:
		{

			hlistbox = CreateWindowEx(NULL, "Listbox", NULL, WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_BORDER, 2, 40, 380, 160, hwnd, (HMENU)IDC_ListBox, GetModuleHandle(NULL), NULL);

			if(!hlistbox)
			{
				MessageBox(hwnd, "Could not create incoming edit box.", "Error", MB_OK | MB_ICONERROR);
			}

			HGDIOBJ hfDefault = GetStockObject(DEFAULT_GUI_FONT);

			// Create outgoing message box
			hEditOut=CreateWindowEx(WS_EX_CLIENTEDGE, "EDIT", "", WS_CHILD|WS_VISIBLE|ES_AUTOVSCROLL|ES_AUTOHSCROLL, 2, 2, 160, 20, hwnd, (HMENU)IDC_EDIT_IN, GetModuleHandle(NULL), NULL);
			
			if(!hEditOut)
			{
				MessageBox(hwnd, "Could not create outgoing edit box.", "Error", MB_OK|MB_ICONERROR);

			}

			SendMessage(hEditOut, WM_SETTEXT, NULL, (LPARAM)"127.0.0.1");

			WSADATA WsaDat;
			nResult = WSAStartup(MAKEWORD(2,2), &WsaDat);

			if (nResult != 0)
			{
				MessageBox(hwnd, "Winsock Initialization Failed", "Critical Error", MB_OK);
				SendMessage(hwnd, WM_DESTROY, 0, 0);
				break;
			}

			memset(&SockAddr, 0, sizeof(sockaddr_in));
			memset(&RecvData, 0, sizeof(RecvData));
			memset(buffer, 0, sizeof(buffer));

			Socket = socket(AF_INET, SOCK_STREAM, 0);
			if (Socket == INVALID_SOCKET)
			{
				MessageBox(hwnd, "Socket creation failed", "Critical Error", MB_OK);
				SendMessage(hwnd, WM_DESTROY, 0, 0);
				break;
			}

			nResult = WSAAsyncSelect(Socket, hwnd, WM_SOCKET, (FD_CONNECT | FD_READ | FD_CLOSE));
			if (nResult)
			{
				MessageBox(hwnd, "WSAAsyncSelect failed", "Critical Error", MB_OK);
				SendMessage(hwnd, WM_DESTROY, 0, 0);
				break;
			}

		}break;
	case WM_PAINT:
		{
			hdc = BeginPaint(hwnd, &ps);
			EndPaint(hwnd, &ps);
			return(0);
		}break;
	case WM_DESTROY:
		{
			closesocket(Socket);
			WSACleanup();
			PostQuitMessage(0);

		}break;
	case WM_COMMAND:
		{
			switch(LOWORD(wParam))
			{
			case MENU_FILE_CONNECT:
				{
					SendMessage(hEditOut, WM_GETTEXT, sizeof(szServer), (LPARAM)(LPSTR)szServer);
					SockAddr.sin_addr.s_addr = inet_addr(szServer);
					SockAddr.sin_family = AF_INET;
					SockAddr.sin_port = htons(2006);

					iResult = connect(Socket, (struct sockaddr*)&SockAddr, sizeof(sockaddr));

					if (iResult == SOCKET_ERROR)
					{
						wsprintf(error, TEXT("Error Code: %d"), WSAGetLastError());
						MessageBox(hwnd, error, "Critical Error", MB_OK);
						return(0);
					}

				}break;
			case MENU_FILE_GET:
				{
					SendBytes = send(Socket, SendData, sizeof(SendData), 0);
					memset(RecvData, 0, sizeof(RecvData));				

				}break;
			default:break;
			}
		}break;
	case WM_SOCKET:
		{
			if (WSAGETSELECTERROR(lParam))
			{
				MessageBox(hwnd, "Connection to server failed", "ERROR", MB_OK);
				SendMessage(hwnd, WM_DESTROY, 0, 0);
				break;
			}
			switch(WSAGETSELECTEVENT(lParam))
			{
			case FD_READ:
				{
					char szIncoming[100];
					ZeroMemory(szIncoming, sizeof(szIncoming));

					RecvBytes = recv(Socket, (char*)szIncoming, sizeof(szIncoming)/sizeof(szIncoming[0]), 0);

					vShowText(hlistbox, szIncoming);


				}break;
			case FD_CONNECT:
				{

				}break;
			case FD_CLOSE:
				{
					closesocket(Socket);

				}break;
			default:break;
			}
		}break;
	}
	return(DefWindowProc(hwnd, uMsg, wParam, lParam));
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
	WNDCLASSEX wc;
	HWND hwnd;

	wc.cbClsExtra = 0;
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.cbWndExtra = 0;
	wc.hbrBackground = HBRUSH(GetStockObject(BLACK_BRUSH));
	wc.hCursor = LoadCursor(hInstance, IDC_ARROW);
	wc.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
	wc.hIconSm = LoadIcon(hInstance, IDI_APPLICATION);
	wc.hInstance = hInstance;
	wc.lpfnWndProc = WinProc;
	wc.lpszClassName = "myClass";
	wc.lpszMenuName = "MainMenu";
	wc.style = CS_VREDRAW | CS_HREDRAW | CS_DBLCLKS | CS_OWNDC;
	
	if (!(RegisterClassEx(&wc)))
	{
		return(0);
	}

	if (!(hwnd = CreateWindowEx(NULL, "myClass", "Async Client", WS_VISIBLE | WS_OVERLAPPEDWINDOW, 200, 200, 800, 600, NULL, NULL, hInstance, NULL)))
	{
		return(0);
	}

	MSG msg;

	while(TRUE)
	{
		GetMessage(&msg, NULL, 0, 0);

		if(msg.message == WM_QUIT)
		{
			break;
		}

		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

return(0);
}

//=============================================================
//function used to display text into the listbox
//=============================================================
void vShowText(HWND	hChildHandle, char *szText)
{
	int Line;
	
	// add string to the listbox
	SendMessage(hChildHandle,LB_ADDSTRING,0,(LPARAM)szText);
	
	// determine number of items in listbox
	Line = SendMessage(hChildHandle,LB_GETCOUNT,0,0);
	
	// flag last item as the selected item, to scroll listbox down
	SendMessage(hChildHandle,LB_SETCURSEL,Line-1,0);
	
	// unflag all items to eliminate negative highlite
	SendMessage(hChildHandle,LB_SETCURSEL,-1,0);
}
Posted
Updated 17-Oct-10 21:10pm
v7
Comments
Sandeep Mewara 13-Jul-10 1:42am    
If there was any error then you should have reported the same here in your question.
I hope you are not expecting, someone to copy your code, run and test it for you!
AspDotNetDev 18-Aug-10 18:41pm    
Sandeep, I'm pretty sure the OP was asking how to make the code a bit more elegant, not how to fix an error. Though, the OP should have mentioned if the desired elegance should be in the area of code clarity, code length, code execution speed, memory usage, or what have you.
AspDotNetDev 18-Aug-10 18:45pm    
OP, you screwed up the formatting of the code. You may want to brush up on HTML encoding and PRE tags... make use of them to format your code better. As it stands, your code is unreadable. I love to make code more elegant, but I'm not even going to look at yours due to the lack of attention to formatting.
Sauro Viti 18-Oct-10 3:11am    
Please, wrap your code into PRE tags: it will be too much more readable!

Probably: as Sandeep says we may help to fix errors but we're not here to prettify your code or teach you how to write efficient code.
 
Share this answer
 
Comments
AspDotNetDev 18-Aug-10 18:47pm    
Sure we are. The OP should probably ask a more specific question (e.g., "how can I remove the excess variables" or "how can I speed up the execution time"), but I for one like to answer questions about efficient code.
Efficiency isn't a problem with code this size. It'll spend more time in GetMessage than anywhere else so there's not a lot to worry about.

Things I would worry about:

- More switches than Frankenstein's lab
- Global variables
- BIG functions, more than 20 lines

So here's what I would do about them...

- Use dispatch tables OR look at the message cracker macros in windowsx.h
- Get rid of the globals, perhaps use GetDialogItem to recover the child window handles
- Split the big functions up into smaller ones that do one thing well. For example move the window class registration into it's own function.

Hope that helps,

Cheers,

Ash
 
Share this answer
 
Comments
Emilio Garavaglia 13-Jul-10 16:23pm    
"More switches than Frankenstein's lab" :-))) Fantastic !

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900