Anda di halaman 1dari 28

// UDPSender.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <winsock2.h> #include <stdio.

h> #include <conio.h> int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret; WSAStartup(wVersion,&wsaData); SOCKET sender; SOCKADDR_IN receiverAddr; sender = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); receiverAddr.sin_family = AF_INET; receiverAddr.sin_port = htons(8888); receiverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); char str[1024]; while (1) { gets(str); strcat(str,"\r\n"); sendto(sender,str,strlen(str),0, (sockaddr*)&receiverAddr, sizeof(receiverAddr)); } getch(); closesocket(sender); WSACleanup(); return 0; } // AsyncSelectDlg.cpp : implementation file #include "stdafx.h" #include "AsyncSelect.h" #include "AsyncSelectDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #define WM_SOCKET WM_USER+1 // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { }

// DDX/DDV support

void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CAsyncSelectDlg dialog CAsyncSelectDlg::CAsyncSelectDlg(CWnd* pParent /*=NULL*/) : CDialog(CAsyncSelectDlg::IDD, pParent) , m_sIpAddress(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CAsyncSelectDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_IPADDRESS, m_ipaddress); DDX_Text(pDX, IDC_IPADDRESS, m_sIpAddress); } BEGIN_MESSAGE_MAP(CAsyncSelectDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON1, &CAsyncSelectDlg::OnBnClickedButton1) END_MESSAGE_MAP() // CAsyncSelectDlg message handlers BOOL CAsyncSelectDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); WSAStartup(wVersion,&wsaData); return TRUE; // return TRUE unless you set the focus to a control }

void CAsyncSelectDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CAsyncSelectDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CAsyncSelectDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CAsyncSelectDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here c = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); char address[128]; int len; int ret; UpdateData(); len = WideCharToMultiByte(CP_ACP,0,m_sIpAddress, m_sIpAddress.GetLength(), address,128,0,0); address[len] = 0; ret = WSAAsyncSelect(c,this->m_hWnd,WM_SOCKET,

FD_READ|FD_WRITE|FD_CONNECT|FD_CLOSE); SOCKADDR_IN serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = inet_addr(address); ret = connect(c,(sockaddr*)&serverAddr,sizeof(serverAddr)); if (ret == SOCKET_ERROR) { ret = WSAGetLastError(); } } LRESULT CAsyncSelectDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class switch(message) { case WM_SOCKET: if (WSAGETSELECTERROR(lParam)) { closesocket(c); MessageBox(L"Li kt ni"); break; }; switch (WSAGETSELECTEVENT(lParam)) { case FD_CONNECT: MessageBox(L"Kt ni thnh cng"); break; } } return CDialog::WindowProc(message, wParam, lParam); }

// AsyncSelectClientDlg.cpp : implementation file #include "stdafx.h" #include "AsyncSelectClient.h" #include "AsyncSelectClientDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #define WM_SOCKET WM_USER+1 // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // Implementation protected: DECLARE_MESSAGE_MAP() };

// DDX/DDV support

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CAsyncSelectClientDlg dialog CAsyncSelectClientDlg::CAsyncSelectClientDlg(CWnd* pParent /*=NULL*/) : CDialog(CAsyncSelectClientDlg::IDD, pParent) , m_sIpAddress(_T("")) , m_sTxtSend(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CAsyncSelectClientDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_sIpAddress); DDX_Control(pDX, IDC_LIST1, m_list); DDX_Text(pDX, IDC_EDIT2, m_sTxtSend); } BEGIN_MESSAGE_MAP(CAsyncSelectClientDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON1, &CAsyncSelectClientDlg::OnBnClickedButton1) ON_BN_CLICKED(IDC_SEND, &CAsyncSelectClientDlg::OnBnClickedSend) ON_EN_CHANGE(IDC_EDIT2, &CAsyncSelectClientDlg::OnEnChangeEdit2) ON_WM_KEYDOWN() END_MESSAGE_MAP() // CAsyncSelectClientDlg message handlers BOOL CAsyncSelectClientDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog

SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); WSAStartup(wVersion,&wsaData); m_sIpAddress = L"127.0.0.1"; UpdateData(0); return TRUE; // return TRUE unless you set the focus to a control } void CAsyncSelectClientDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CAsyncSelectClientDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CAsyncSelectClientDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon);

} void CAsyncSelectClientDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here c = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); UpdateData(); char address[128]; int len; len = WideCharToMultiByte(CP_ACP,0,m_sIpAddress, m_sIpAddress.GetLength(), address, 128,0,0); address[len]=0; WSAAsyncSelect(c,this->m_hWnd,WM_SOCKET, FD_CONNECT|FD_READ|FD_WRITE|FD_CLOSE); SOCKADDR_IN serverAddr; serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = inet_addr(address); connect(c,(sockaddr*)&serverAddr, sizeof(serverAddr));; } LRESULT CAsyncSelectClientDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) { // TODO: Add your specialized code here and/or call the base class char ansi[1024]; wchar_t unicode[1024]; wchar_t str[1024]; int len; switch(message) { case WM_SOCKET: if (WSAGETSELECTERROR(lParam)) { closesocket(c); switch(WSAGETSELECTEVENT(lParam)) { case FD_CONNECT: MessageBox(L"Li kt ni n server"); break; case FD_CLOSE: MessageBox(L"Kt ni b ng!"); } break; }; switch (WSAGETSELECTEVENT(lParam)) { case FD_CONNECT: MessageBox(L"Kt ni thnh cng n server!"); break; case FD_READ: /* len = recv(c,ansi,1024,0);

len = MultiByteToWideChar(CP_ACP,0, ansi,len, unicode, 1024); unicode[len-1] = 0; */ len = recv(c,(char*)unicode,2048,0); unicode[len/2] = 0; wcscpy(str,L"Server:"); wcscat(str,unicode); m_list.AddString(str); break;

} } return CDialog::WindowProc(message, wParam, lParam); } void CAsyncSelectClientDlg::OnBnClickedSend() { // TODO: Add your control notification handler code here char ansi[1024]; int len; UpdateData(); /* len = WideCharToMultiByte(CP_ACP,0,m_sTxtSend, m_sTxtSend.GetLength(), ansi, 1024,0,0); ansi[len] = 0; send(c,ansi,len,0); */ send(c,(char*)m_sTxtSend.GetBuffer(), m_sTxtSend.GetLength()*2,0); m_list.AddString(L"You:"+m_sTxtSend); m_sTxtSend = L""; UpdateData(0); } void CAsyncSelectClientDlg::OnEnChangeEdit2() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: } Add your control notification handler code here

void CAsyncSelectClientDlg::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { // TODO: Add your message handler code here and/or call default if (nChar==0x13) { } CDialog::OnKeyDown(nChar, nRepCnt, nFlags); }

// AsyncSelectServer.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "AsyncSelectServer.h" #include "AsyncSelectServerDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CAsyncSelectServerApp BEGIN_MESSAGE_MAP(CAsyncSelectServerApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CAsyncSelectServerApp construction CAsyncSelectServerApp::CAsyncSelectServerApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CAsyncSelectServerApp object CAsyncSelectServerApp theApp; // CAsyncSelectServerApp initialization BOOL CAsyncSelectServerApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls);

CWinApp::InitInstance(); AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CAsyncSelectServerDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel } // Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }

// AsyncSocket.cpp : Defines the class behaviors for the application. // #include #include #include #include "stdafx.h" "MySocket.h" "AsyncSocket.h" "AsyncSocketDlg.h"

#ifdef _DEBUG #define new DEBUG_NEW #endif // CAsyncSocketApp BEGIN_MESSAGE_MAP(CAsyncSocketApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() // CAsyncSocketApp construction CAsyncSocketApp::CAsyncSocketApp()

{ // TODO: add construction code here, // Place all significant initialization in InitInstance } // The one and only CAsyncSocketApp object CAsyncSocketApp theApp; // CAsyncSocketApp initialization BOOL CAsyncSocketApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); if (!AfxSocketInit()) { AfxMessageBox(IDP_SOCKETS_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("Local AppWizard-Generated Applications")); CAsyncSocketDlg dlg; m_pMainWnd = &dlg; INT_PTR nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel }

// Since the dialog has been closed, return FALSE so that we exit the // application, rather than start the application's message pump. return FALSE; }

// BetterBlockingServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <stdio.h> #include <conio.h> SOCKET server; SOCKET clients[64]; SOCKADDR_IN serverAddr; SOCKADDR_IN clientAddrs[64]; int nClients,clientAddrLen; DWORD WINAPI DocBanPhim(LPVOID lpParam) { char str[1024]; int i; while (1) { gets(str); strcat(str,"\r\n"); for (i=0;i<nClients;i++) if(clients[i]!=SOCKET_ERROR) { send(clients[i],str,strlen(str),0); } } } DWORD WINAPI ReceiverThread(LPVOID lpParam) { int index = (int)lpParam; char str[1024]; int ret; while (1) { ret = recv(clients[index],str,1024,0); if (ret<=0) { closesocket(clients[index]); clients[index] = SOCKET_ERROR; break; }; str[ret] = 0; printf("[%s:%d]: %s\n", inet_ntoa(clientAddrs[index].sin_addr), htons(clientAddrs[index].sin_port), str); for (int i = 0;i<nClients;i++) if ((clients[i]!=SOCKET_ERROR)&&

(i!=index)) send(clients[i],str,strlen(str),0);

}; return 0; } int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret = 0; bool bFirstClient = true; WSAStartup(wVersion,&wsaData); server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); ret = bind(server,(sockaddr*)&serverAddr, sizeof(serverAddr)); if (ret==SOCKET_ERROR) { printf("Loi %d",WSAGetLastError()); closesocket(server); WSACleanup(); getch(); return 0; }; ret = listen(server,10); int i; for (i = 0;i<64;i++) clients[i] = SOCKET_ERROR; nClients = 0; while (1) { for (i=0;i<nClients;i++) if (clients[i]==SOCKET_ERROR) break; clientAddrLen = sizeof(SOCKADDR_IN); clients[i] = accept(server, (sockaddr*)&clientAddrs[i], &clientAddrLen); if (bFirstClient) { CreateThread(0,0,DocBanPhim,0,0,0); bFirstClient = false; }; CreateThread(0,0,ReceiverThread,(LPVOID)i,0,0); nClients++; } closesocket(server); for (i = 0;i<nClients;i++) if (clients[i]!=SOCKET_ERROR) closesocket(clients[i]);

WSACleanup(); getch(); return 0; }

// BetterSelectServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); // Khi to WinSock WSAStartup(wVersion,&wsaData); // Khai bo socket cho server SOCKET s; // Khai bo mng socket cho client SOCKET c[64]; // Bin m s lng socket ti a // s dng int nClient = 0; SOCKADDR_IN sAddr;// a ch server SOCKADDR_IN cAddrs[64];// a ch client int i,ret; // Khi to mng cc socket client for (i=0;i<64;i++) c[i] = SOCKET_ERROR; // To socket cho server s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); sAddr.sin_family = AF_INET; sAddr.sin_port = htons(8888); sAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Gn a ch cho socket server ret = bind(s,(sockaddr*)&sAddr, sizeof(sAddr)); // Chuyn server sang trng thi i // kt ni ret = listen(s,10); fd_set readfds; char str[1024]; while (1) { // Xa tp readfds FD_ZERO(&readfds); // Cho s vo tp thm d FD_SET(s,&readfds); // Cho cc client hp l vo tp // thm d for (i=0;i<nClient;i++)

if (c[i]!=SOCKET_ERROR) FD_SET(c[i],&readfds); // Thc hin thm d s kin ret = select(0,&readfds,0,0,0); if (ret<0) break; if (FD_ISSET(s,&readfds)) // Nu c kt ni mi { // Tm mt ch trng trong mng // c cho socket vo for (i=0;i<nClient;i++) if (c[i]==SOCKET_ERROR) break; if (i<64) // Nu cha 64 kt ni // => thm c { int cLen = sizeof(SOCKADDR_IN); // Chp nhn kt ni mi c[i] = accept(s,(sockaddr*)&cAddrs[i], &cLen); // Hin thng tin v kt ni mi printf("Co ket noi moi tu %s:%d\n", inet_ntoa(cAddrs[i].sin_addr), htons(cAddrs[i].sin_port)); nClient++; } else { SOCKET tmp; SOCKADDR_IN tmpAddr; int tmpLen = sizeof(tmpAddr); tmp = accept(s,(sockaddr*)&tmpAddr, &tmpLen); closesocket(tmp); printf("Khong tiep khach nua :-w"); } } int len = 0; for (i=0;i<nClient;i++) if (c[i]!=SOCKET_ERROR) if (FD_ISSET(c[i],&readfds)) { len = recv(c[i],str,1024,0); if (len>0) { str[len] = 0; printf("Client %d:%s\n",i,str); } else { closesocket(c[i]); c[i] = SOCKET_ERROR; } } }

return 0; } ,0 FILE * fp; char buff[1024]; int len; fp = fopen("name.txt","rb"); while (!feof(fp)) { len = fread(buff,1,1024,fp); if (len } // BlockingClient.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <stdio.h> #include <conio.h> SOCKET s; DWORD WINAPI ReceiverThread(LPVOID lpParam) { char str[1024]; int ret; while (1) { ret = recv(s,str,1024,0); if (ret>0) { str[ret] = 0; printf("Server:%s\n",str); } else { printf("Ket noi da bi dong!"); break; } } return 0; } int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret; ret = WSAStartup(wVersion,&wsaData); SOCKADDR_IN serverAddr; char diachi[128]; while(1) {

printf("Nhap dia chi ip cua server:"); gets(diachi); if(inet_addr(diachi)!=INADDR_NONE) break; else printf("Dia chi khong hop le!\n"); }; s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = inet_addr(diachi); ret = connect(s,(sockaddr*)&serverAddr, sizeof(serverAddr)); if (ret==SOCKET_ERROR) { printf("Loi %d",WSAGetLastError()); getch(); closesocket(s); WSACleanup(); return 0; }; printf("Da ket noi den server!\n"); CreateThread(0,0,ReceiverThread,0,0,0); char str[1024]; while(1) { gets(str); send(s,str,strlen(str),0); } getch(); closesocket(s); WSACleanup(); return 0; }

// FileServer.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <conio.h> #include <stdio.h> SOCKET s; SOCKET c[64]; SOCKADDR_IN sAddr; SOCKADDR_IN cAddrs[64]; int nClients; int cAddrLen = sizeof(SOCKADDR_IN); DWORD WINAPI HandleClient(LPVOID lpParam) { int index = (int)lpParam; char str[1024];

char command[1024]; char reply[1024]; char filename[1024]; int len = 0; command[0] = 0; while (1) { len = recv(c[index],str,1024,0); if (len>0) { strcat(command,str); if (strchr(command,'\n')!=0) { if(strstr(command,"GET ")==command) { strncpy(filename,command+4, strchr(command,'\n')-command-4); filename[strchr(command,'\n')-command-4]=0; break; } else { strcpy(reply,"FAILED\nInvalid command\n\n"); send(c[index],reply,strlen(reply),0); closesocket(c[index]); c[index] = SOCKET_ERROR; return 0; } } } }; printf("Client yeu cau file:%s\n",filename); FILE * fp; int filelen = 0; fp = fopen(filename,"rb"); if (!fp) { strcpy(reply,"FAILED\nFile not found\n\n"); send(c[index],reply,strlen(reply),0); closesocket(c[index]); c[index] = SOCKET_ERROR; return 0; }; fseek(fp,0,SEEK_END); filelen = ftell(fp); fseek(fp,0,SEEK_SET); sprintf(reply,"OK\n%d\n\n",filelen); send(c[index],reply,strlen(reply),0); char buff[1024]; while (!feof(fp)) { len = fread(buff,1,1024,fp); send(c[index],buff,len,0); }; fclose(fp);

closesocket(c[index]); c[index]=SOCKET_ERROR; printf("Gui xong !"); return 0; } int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); int ret = 0; int i; s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); sAddr.sin_family = AF_INET; sAddr.sin_addr.s_addr = htonl(INADDR_ANY); sAddr.sin_port = htons(8888); ret = bind(s,(sockaddr*)&sAddr,sizeof(sAddr)); if (ret==SOCKET_ERROR) { printf("Loi %d",WSAGetLastError()); // Xu ly loi... return 0; }; listen(s,10); nClients = 0; for (i=0;i<64;i++) c[i] = SOCKET_ERROR; while (1) { for (i=0;i<nClients;i++) if (c[i] == SOCKET_ERROR) break; c[i]= accept(s,(sockaddr*)&cAddrs[i], &cAddrLen); CreateThread(0,0,HandleClient,(LPVOID)i,0,0); } return 0; }

// MFCSocket.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "MFCSocket.h" #include <afxsock.h> #ifdef _DEBUG #define new DEBUG_NEW #endif // The one and only application object CWinApp theApp;

using namespace std; int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { int nRetCode = 0; // initialize MFC and print and error on failure if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) { // TODO: change error code to suit your needs _tprintf(_T("Fatal Error: MFC initialization failed\n")); nRetCode = 1; } else { client.Create(); client.Connect(L"127.0.0.1",8888); char str[1024]; strcpy(str,"Hello CSocket"); client.Send(str,strlen(str)); client.Close(); } return nRetCode; }

using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; namespace NETTCPClient { class Program { static void Main(string[] args) { IPAddress address = Dns.GetHostAddresses("www.google.com")[1]; IPEndPoint ie = new IPEndPoint( address, 8888); Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { s.Connect(ie); byte[] data = new byte[1024]; int ret; ret = s.Receive(data); string str = Encoding.ASCII.GetString(data, 0, ret); Console.WriteLine("Server gui:{0}", str); string input; while (true) {

input = Console.ReadLine(); //Chuyen input thanh mang byte gui len cho server data = Encoding.ASCII.GetBytes(input); s.Send(data, data.Length, SocketFlags.None); }; } catch (SocketException e) { Console.WriteLine("Loi:{0}", e.Message); Console.ReadKey(); } } } } using using using using using System; System.Collections.Generic; System.Text; System.Net; System.Net.Sockets;

namespace NETTCPServer { class Program { static void Main(string[] args) { IPEndPoint ie = new IPEndPoint(IPAddress.Any, 8888); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); int ret; try { server.Bind(ie); server.Listen(10); Socket client = server.Accept(); Console.WriteLine("Chap nhan ket noi tu:{0}", client.RemoteEndPoint.ToString()); string s = "Hello Net Socket"; byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.Send(data, data.Length, SocketFlags.None); while (true) { data = new byte[1024]; ret = client.Receive(data); if (ret == 0) break; Console.WriteLine("Du lieu tu client:{0}", Encoding.ASCII.GetString(data, 0, ret)); }

client.Shutdown(SocketShutdown.Both); client.Close(); } catch (SocketException e) { Console.WriteLine("Loi:{0}!", e.Message); Console.ReadKey(); return; } catch (ObjectDisposedException e) { Console.WriteLine("Loi:{0}!", e.Message); Console.ReadKey(); return; } } } }

// Overlapped-Completion.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <stdio.h> #include <conio.h> SOCKET s; OVERLAPPED overlapped; char buff[1024]; WSABUF databuff; DWORD flags; DWORD bytesReceived = 0; int ret = 0; void CALLBACK CompletionRoutine( IN DWORD dwError, IN DWORD cbTransferred, IN LPWSAOVERLAPPED lpOverlapped, IN DWORD dwFlags) { if (dwError != 0||cbTransferred==0) // X l li { closesocket(s); return; }; // Hin th xu ra mn hnh buff[cbTransferred]=0; printf(buff); // Khi to li cu trc overlapped v li gi tip yu cu nhn d liu memset(&overlapped,0,sizeof(overlapped)); flags = 0;

ret = WSARecv(s, &databuff, 1, &bytesReceived, &flags, &overlapped, CompletionRoutine); if (ret == SOCKET_ERROR) { ret = WSAGetLastError(); if (ret != WSA_IO_PENDING) printf("Loi %d !\n",ret); }; return; } int _tmain(int argc, _TCHAR* argv[]) { // Khi to v kt ni n 127.0.0.1:8888 WSADATA wsaData; WSAStartup(MAKEWORD(2,2),&wsaData); SOCKADDR_IN sAddr; sAddr.sin_family = AF_INET; sAddr.sin_port = htons(8888); sAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); ret = connect(s,(sockaddr*)&sAddr,sizeof(sAddr)); // Khi to cu trc overlapped memset(&overlapped,0,sizeof(overlapped)); // Khi to b m d liu databuff.buf = buff; databuff.len = 1024; // Gi yu cu vo ra ret = WSARecv(s, &databuff,1,&bytesReceived,&flags,&overlapped, CompletionRoutine); // X l li // Chuyn lung sang trng thi alertable while (1) SleepEx(1000,TRUE); getch(); closesocket(s); WSACleanup(); return 0; return 0; }

// SelectServer.cpp : Defines the entry point for the console application. // #include #include #include #include "stdafx.h" <winsock2.h> <stdio.h> <conio.h>

int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret;

WSAStartup(wVersion,&wsaData); SOCKET s,c = SOCKET_ERROR; SOCKADDR_IN sAddr,cAddr; int cLen; s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); sAddr.sin_family = AF_INET; sAddr.sin_addr.s_addr = htonl(INADDR_ANY); sAddr.sin_port = htons(8888); ret = bind(s,(sockaddr*)&sAddr,sizeof(sAddr)); ret = listen(s,10); fd_set readfds; char str[1024]; while (1) { FD_ZERO(&readfds); if (c==SOCKET_ERROR) FD_SET(s,&readfds); if (c!=SOCKET_ERROR) FD_SET(c,&readfds); ret = select(0,&readfds,0,0,0); if (ret<=0) { printf("Loi %d",WSAGetLastError()); break; }; if (FD_ISSET(s,&readfds)) { if (c==SOCKET_ERROR) // Cha dng socket c { cLen = sizeof(cAddr); c = accept(s,(sockaddr*)&cAddr,&cLen); printf("Co khach den choi\n"); } else { printf("Khong the tiep them khach nua,sorry!"); } }; if (c!=SOCKET_ERROR) if (FD_ISSET(c,&readfds)) { ret = recv(c,str,1024,0); if (ret<=0) { printf("Loi %d",WSAGetLastError()); continue; };

str[ret] = 0; printf("Client:%s\n",str); } }

return 0; } // TCPClient.cpp : Defines the entry point for the console application. // #include #include #include #include "stdafx.h" <winsock2.h> <stdio.h> <conio.h>

int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret; ret = WSAStartup(wVersion,&wsaData); SOCKET s; SOCKADDR_IN serverAddr; char diachi[128]; while(1) { printf("Nhap dia chi ip cua server:"); gets(diachi); if(inet_addr(diachi)!=INADDR_NONE) break; else printf("Dia chi khong hop le!\n"); }; s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = inet_addr( ); ret = connect(s,(sockaddr*)&serverAddr, sizeof(serverAddr)); if (ret==SOCKET_ERROR) { printf("Loi %d",WSAGetLastError()); getch(); closesocket(s); WSACleanup(); return 0; }; printf("Da ket noi den server!\n");

char str[1024]; while(1) { ret = recv(s,str,1024,0); if (ret>0) { str[ret]=0; printf("Server:%s",str); } else { printf("Ket noi da bi ngat!"); break; }; gets(str); send(s,str,strlen(str),0); } getch(); closesocket(s); WSACleanup(); return 0; } // TCPServer.cpp : Defines the entry point for the console application. // #include #include #include #include "stdafx.h" <winsock2.h> <stdio.h> <conio.h>

int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret ; ret = WSAStartup(wVersion,&wsaData); SOCKET server,client; SOCKADDR_IN serverAddr,clientAddr; int clientAddrLen = sizeof(clientAddr); server = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(8888); serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); ret = bind(server,(sockaddr*)&serverAddr, sizeof(serverAddr)); if (ret == SOCKET_ERROR) { printf("Khong mo duoc cong 8888!"); closesocket(server); WSACleanup(); getch(); return 0;

}; ret =listen(server,10); client = accept(server,(sockaddr*)&clientAddr, &clientAddrLen); printf("Co ket noi moi tu %s:%d\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port)); char buff[1024]; while(1) { gets(buff); strcat(buff,"\r\n"); ret = send(client,buff,strlen(buff),0); ret = recv(client,buff,1024,0); buff[ret]=0; printf("Client:%s\n",buff); } getch(); closesocket(server); WSACleanup(); return 0; } // UDPFileTransfer.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <windows.h> struct Packet { BYTE type; char sender[32]; char receiver[32]; int length; WORD checksum; int offset; BYTE data[65536]; } int _tmain(int argc, _TCHAR* argv[]) { char buff[1024]; Packet pk; pk.type = 0x01; strcpy(pk.sender,"abc"); strcpy(pk.receiver,"def"); pk.length = 1024; pk.checksum = 0x1234; pk.offset = 0; memcpy(pk.data,buff,pk.length); sendto(s,&pk,75+pk.length,0,&cAddr,sizeof(cAddr)); recvfrom(s,&pk,75,....); ..

recvfrom(s,pk.data,pk.length,0,...); return 0; } // UDPReceiver.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <winsock2.h> #include <stdio.h> #include <conio.h> int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WORD wVersion = MAKEWORD(2,2); int ret; WSAStartup(wVersion,&wsaData); SOCKET receiver; receiver = socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP); SOCKADDR_IN receiverAddr,senderAddr; int senderAddrLen = sizeof(senderAddr); receiverAddr.sin_family = AF_INET; receiverAddr.sin_port = htons(8888); receiverAddr.sin_addr.s_addr = htonl(INADDR_ANY); ret = bind(receiver,(sockaddr*)&receiverAddr, sizeof(receiverAddr)); if (ret==SOCKET_ERROR) { printf("Loi %d",WSAGetLastError()); closesocket(receiver); WSACleanup(); getch(); return 0; }; char str[1024]; while (1) { ret = recvfrom(receiver,str,1024,0, (sockaddr*)&senderAddr, &senderAddrLen); if (ret<=0) break; str[ret]=0; printf("[%s:%d]%s\n", inet_ntoa(senderAddr.sin_addr), ntohs(senderAddr.sin_port),str); }; getch(); closesocket(receiver); WSACleanup(); return 0; }

Anda mungkin juga menyukai