📄 winsockcomm_new.cpp
字号:
// WinsockComm.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "WinsockComm.h"
#include <commctrl.h>
// Vincent added codes here to include header files
#include <stdio.h>
#include <string.h>
#include <windows.h>
#include <winsock2.h>
#include <Winuser.h>
#include <Pwinreg.h>
#include <Iphlpapi.h>
#include <IpTypes.h>
#include <Ws2tcpip.h>
#define MAX_LOADSTRING 100
// Vincent added codes here to define constants
#define DEFAULT_PORT "1234"
#define BUFFER_SIZE 23 // length of "WinCE Echo Test Packet"
#define TIMEOUT_SECS 2
#define TIMEOUT_USECS 0
char pBuf[] = "WinCE Echo Test Packet";
// Global Variables:
HINSTANCE hInst; // The current instance
HWND hwndCB; // The command bar handle
// Forward declarations of functions included in this code module:
ATOM MyRegisterClass (HINSTANCE, LPTSTR);
BOOL InitInstance (HINSTANCE, int);
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About (HWND, UINT, WPARAM, LPARAM);
// Vincent added codes here to declair global variables and functions
LRESULT CALLBACK DoDemo (HWND, UINT, WPARAM, LPARAM);
BOOL GetLANinfo(HWND hDlg);
char * ConvertUnicodeToAscii(LPCWSTR p,int l);
void Print(TCHAR *pFormat, ...);
IP_ADAPTER_INFO gStrucAdpInfo[4];
DWORD WINAPI ServerThread (PVOID pArg);
DWORD WINAPI ClientThread (PVOID pArg);
DWORD WINAPI ClientStart(PVOID pArg);
char *gIPaddress, *gPortNumber;
HANDLE hServerThread = INVALID_HANDLE_VALUE;
HANDLE hClientThread = INVALID_HANDLE_VALUE;
HWND gDemoDlg = NULL;
SOCKET gClientSocket;
ADDRINFO *gServerAddrInfo;
int _tmainClient(void);
#define DEFAULT_FAMILY AF_UNSPEC
#define DEFAULT_SOCKTYPE SOCK_STREAM
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MSG msg;
HACCEL hAccelTable;
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_WINSOCKCOMM);
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// It is important to call this function so that the application
// will get 'well formed' small icons associated with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance, LPTSTR szWindowClass)
{
WNDCLASS wc;
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = (WNDPROC) WndProc;
wc.cbClsExtra = 0;
wc.cbWndExtra = 0;
wc.hInstance = hInstance;
wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WINSOCKCOMM));
wc.hCursor = 0;
wc.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wc.lpszMenuName = 0;
wc.lpszClassName = szWindowClass;
return RegisterClass(&wc);
}
//
// 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)
{
HWND hWnd;
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The window class name
hInst = hInstance; // Store instance handle in our global variable
// Initialize global strings
LoadString(hInstance, IDC_WINSOCKCOMM, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance, szWindowClass);
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
hWnd = CreateWindow(szWindowClass, szTitle, WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
if (hwndCB)
CommandBar_Show(hwndCB, TRUE);
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)
{
switch (message)
{
case WM_COMMAND:
break;
case WM_CREATE:
DialogBox(hInst, (LPCTSTR)IDD_DIALOG_DEMO, hWnd, (DLGPROC)DoDemo);
DestroyWindow(hWnd);
break;
case WM_PAINT:
break;
case WM_DESTROY:
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// ================================
// Vincent added all codes below
// ================================
LRESULT CALLBACK DoDemo(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
RECT rt, rt1;
int DlgWidth, DlgHeight; // dialog width and height in pixel units
int NewPosX, NewPosY;
// Added by Vincent
TCHAR tchBuffer[20];
UINT cntText;
WSADATA wsaData;
DWORD dwTStat;
gDemoDlg = hDlg;
switch (message)
{
case WM_INITDIALOG:
// trying to center the About dialog
if (GetWindowRect(hDlg, &rt1)) {
GetClientRect(GetParent(hDlg), &rt);
DlgWidth = rt1.right - rt1.left;
DlgHeight = rt1.bottom - rt1.top ;
NewPosX = (rt.right - rt.left - DlgWidth)/2;
NewPosY = (rt.bottom - rt.top - DlgHeight)/2;
// if the About box is larger than the physical screen
if (NewPosX < 0) NewPosX = 0;
if (NewPosY < 0) NewPosY = 0;
SetWindowPos(hDlg, 0, NewPosX, NewPosY,
0, 0, SWP_NOZORDER | SWP_NOSIZE);
}
// Vincent added code here
SendDlgItemMessage(hDlg, IDC_COMBO_ROLE, CB_INSERTSTRING , -1, (LPARAM)(LPCSTR)TEXT("Server"));
SendDlgItemMessage(hDlg, IDC_COMBO_ROLE, CB_INSERTSTRING , -1, (LPARAM)(LPCSTR)TEXT("Client"));
SendDlgItemMessage(hDlg, IDC_COMBO_ROLE, CB_SETCURSEL, 0, 0);
// Initiate WinSock Library
if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
// WSAStartup failed
return FALSE;
}
// Get Local IP and show in IP edit box
if (!GetLANinfo(hDlg))
{
MessageBox(hDlg, TEXT("Get Local IP Failed"), TEXT("LAN info"), MB_OK);
return FALSE;
}
// Set Default Port Number and show in edit box
SetDlgItemText(hDlg, IDC_EDIT_PORT, TEXT("8000"));
return TRUE;
case WM_COMMAND:
if ((LOWORD(wParam) == IDOK) || (LOWORD(wParam) == IDCANCEL))
{
// Added by Vincent
WSACleanup();
free(gIPaddress);
free(gPortNumber);
freeaddrinfo(gServerAddrInfo);
if(gClientSocket != INVALID_SOCKET)
{
shutdown(gClientSocket, SD_BOTH);
closesocket(gClientSocket);
}
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
// All codes below are added by Vincent
else if (LOWORD(wParam) == IDC_BUTTON_OPEN)
{
// Get IP specified
cntText = GetDlgItemText(hDlg, IDC_EDIT_IP, tchBuffer, sizeof(tchBuffer));
gIPaddress = ConvertUnicodeToAscii(tchBuffer, cntText);
// Get Port Number
cntText = GetDlgItemText(hDlg, IDC_EDIT_PORT, tchBuffer, sizeof(tchBuffer));
gPortNumber = ConvertUnicodeToAscii(tchBuffer, cntText);
// Create Server/Client Thread
switch (SendDlgItemMessage (hDlg, IDC_COMBO_ROLE, CB_GETCURSEL, 0, 0))
{
case 0 :
if (!GetExitCodeThread (hServerThread, &dwTStat) || (dwTStat != STILL_ACTIVE))
{
hServerThread = CreateThread (NULL, 0, ServerThread, hDlg, 0, &dwTStat);
if (hServerThread)
CloseHandle (hServerThread);
}
break;
case 1 : // client
_tmainClient();
// ClientStart(hDlg);
break;
default :
break;
}
}
else if (LOWORD(wParam) == ID_SENDBTN)
{
ClientThread(hDlg);
}
else
{
}
break;
}
return FALSE;
}
BOOL GetLANinfo(HWND hDlg)
{
ULONG uLong;
DWORD dw;
uLong=sizeof(gStrucAdpInfo);
TCHAR strBuffer[100];
if ((dw=GetAdaptersInfo(gStrucAdpInfo, &uLong))==ERROR_SUCCESS)
{
wsprintf(strBuffer, TEXT("%hs"), gStrucAdpInfo[0].IpAddressList.IpAddress.String);
SetDlgItemText(hDlg, IDC_EDIT_IP, strBuffer);
}
else
{
return 0;
}
return 1;
}
//======================================================================================
void Print(TCHAR *pFormat, ...)
{
va_list ArgList;
TCHAR Buffer[256];
va_start (ArgList, pFormat);
(void)wvsprintf (Buffer, pFormat, ArgList);
SendDlgItemMessage (gDemoDlg, ID_RCVTEXT, EM_REPLACESEL, 0, (LPARAM)Buffer);
va_end(ArgList);
}
DWORD WINAPI ServerThread (PVOID pArg)
{
SOCKET sock, SockServ;
SOCKADDR_STORAGE ssRemoteAddr;
int cbRemoteAddrSize, cbXfer, cbTotalRecvd;
ADDRINFO Hints, *AI=NULL;
char pBuf[BUFFER_SIZE];
char szRemoteAddrString[128];
HWND hDlg;
hDlg = (HWND)pArg;
sock = INVALID_SOCKET;
//
// Get a list of available addresses to serve on
//
memset(&Hints, 0, sizeof(Hints));
Hints.ai_family = AF_UNSPEC;
Hints.ai_socktype = SOCK_STREAM;
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
if(getaddrinfo(NULL, gPortNumber, &Hints, &AI))
{
Print(TEXT("ERROR: getaddrinfo failed with error %d\r\n"), WSAGetLastError());
goto Cleanup;
}
// Create socket
SockServ = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
if (SockServ != INVALID_SOCKET)
{
if (bind(SockServ, AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
closesocket(SockServ);
else
{
if (listen(SockServ, 5) == SOCKET_ERROR)
{
closesocket(SockServ);
}
Print(
TEXT("Socket 0x%08x ready for connection with %hs family, %hs type, on port %hs\r\n"),
SockServ,
(AI->ai_family == AF_INET) ? "AF_INET" : ((AI->ai_family == AF_INET6) ? "AF_INET6" : "UNKNOWN"),
(AI->ai_socktype == SOCK_STREAM) ? "TCP" : ((AI->ai_socktype == SOCK_DGRAM) ? "UDP" : "UNKNOWN"),
gPortNumber);
}
}
freeaddrinfo(AI);
//
// Wait for incomming data/connections
//
cbRemoteAddrSize = sizeof(ssRemoteAddr);
while (1)
{
sock = accept(SockServ, (SOCKADDR*)&ssRemoteAddr, &cbRemoteAddrSize);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -