Сокеты пример клиент-серверной программы
Primary tabs
Forums:
пример = http://www.cplusplus.com/forum/windows/1...
клиент =
// client.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <string> #include <iostream> #pragma comment( lib, "ws2_32.lib" ) #include <Windows.h> #include <conio.h> #define len 20 int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WSAStartup(MAKEWORD(2,0),&wsaData); SOCKET s; s=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(2301); addr.sin_addr.s_addr= inet_addr("127.0.0.1"); connect(s, (SOCKADDR*)&addr, sizeof(SOCKADDR)); char buf[len]; while(int i = 1) { connect(s, (SOCKADDR*)&addr, sizeof(SOCKADDR)); printf("put any symbol to send a message to the server \n"); getchar(); strcpy(buf,"My message \n"); send(s, buf,20,0); } shutdown(s,0); closesocket(s); WSACleanup(); _getch(); }
сервер=
// server.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #pragma comment( lib, "ws2_32.lib" ) #include <Windows.h> #include <conio.h> #define len 20 using namespace std; int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsaData; WSAStartup(MAKEWORD(2,0),&wsaData); SOCKET s; s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(2301); addr.sin_addr.s_addr= htonl(INADDR_ANY); bind(s, (SOCKADDR*)&addr, sizeof(addr)); if(listen(s, 1)) return 0; int isize= sizeof(addr); SOCKET n = accept(s, (struct sockaddr*)&addr, &isize); char buf[20]; while(int i = 1) // "бесконечный" цикл { recv(n, buf, len, 0); if(buf[0] != '9') cout << buf << std::endl; buf[0] = '9'; // блокировка повторного вывода } shutdown(s,0); closesocket(s); WSACleanup(); _getch(); }
- Log in to post comments
- 2724 reads