Socket网络编程
在C-Free中建立一个对话框工程,取名Socket1,建立如下文件结构:
Main.h
#ifndef _MAIN_H
#define _MAIN_H
#include <windows.h>
BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam);
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify);
void Main_OnClose(HWND hwnd);
void SocketTest();
void ShowError();
#endif
Main.cpp
#include <windows.h>
#include <windowsx.h>
#include <winsock2.h>
#include "main.h"
#include "dialogs.h"
#include "resource.h"
//#pragmacomment(lib,"libwsock32.a")
BOOL WINAPI Main_Proc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
//BEGIN MESSAGE CRACK
HANDLE_MSG(hWnd, WM_INITDIALOG, Main_OnInitDialog);
HANDLE_MSG(hWnd, WM_COMMAND, Main_OnCommand);
HANDLE_MSG(hWnd,WM_CLOSE, Main_OnClose);
//END MESSAGE CRACK
}
return FALSE;
}
// Main_OnInitDialog
BOOL Main_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam)
{
// Set app icons
HICON hIcon = LoadIcon((HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE) ,MAKEINTRESOURCE(IDI_ICONAPP));
SendMessage(hwnd, WM_SETICON, TRUE, (LPARAM)hIcon);
SendMessage(hwnd, WM_SETICON, FALSE, (LPARAM)hIcon);
//
// Add initializing code here
//
return TRUE;
}
// Main_OnCommand
void Main_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch(id)
{
case IDC_OK:
SocketTest();
//MessageBox(hwnd,"You click OK!","socket1",MB_OK);
//EndDialog(hwnd, id);
break;
case IDC_CANCEL:
MessageBox(hwnd,"You click Cancel!","socket1",MB_OK);
EndDialog(hwnd, id);
break;
default:break;
}
}
void SocketTest()
{
WSADATA wsaData;
//初始化Socket库
WSAStartup(MAKEWORD(2,0),&wsaData);
//创建一根电线
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN sa;
sa.sin_family=AF_INET;
//设置电线连接服务器端的端口
sa.sin_port = htons(IPPORT_SMTP);
//123.125.50.135是ping smtp.163.com出来的,后面会讲使用gethostbyname来直接从
//主机名得到ip地址
sa.sin_addr.S_un.S_addr = inet_addr("113.108.225.9");
//为什么不用设置客户端的端口,难道不需要客户端的端口吗?
if(connect(sock,(SOCKADDR *)&sa,sizeof(sa))==SOCKET_ERROR)
{
ShowError();
return;
}
//接收网易邮件STMP服务器选框消息
TCHAR buff[256];
ZeroMemory(buff,sizeof(buff)/sizeof(TCHAR));
recv(sock,buff,sizeof(buff)/sizeof(TCHAR),0);
MessageBox(NULL,buff,TEXT("返回消息"),MB_OK);
TCHAR hello[]="QUIT/n";
send(sock,hello,sizeof(hello)/sizeof(TCHAR),0);
//再次接收返回的消息
ZeroMemory(buff,sizeof(buff)/sizeof(TCHAR));
recv(sock,buff,sizeof(buff)/sizeof(TCHAR),0);
MessageBox(NULL,buff,TEXT("返回消息"),MB_OK);
closesocket(sock);
WSACleanup();
}
void ShowError()
{
TCHAR* lpMsgBuf;
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER| //自动分配消息缓冲区
FORMAT_MESSAGE_FROM_SYSTEM, //从系统获取信息
NULL,GetLastError(), //获取错误信息标识
MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),//使用系统缺省语言
(LPTSTR)&lpMsgBuf, //消息缓冲区
0,
NULL);
MessageBox(NULL,lpMsgBuf,"",MB_ICONERROR);
}
// Main_OnClose
void Main_OnClose(HWND hwnd)
{
EndDialog(hwnd, 0);
}