Новичок
Профиль
Группа: Участник
Сообщений: 28
Регистрация: 20.1.2007
Репутация: нет Всего: нет
|
Добрый день, вот сижу пишу клиент сервер простенький, цель обменяться сообщениями, прога включает в себя как и серверную, так и клиентскую часть....Сервер инициализируеться нормально, но вот клиент....ммм....не подключаеться к серверу... выдает ошибку 10049.....все пересматрел, ниче не пойму.... Код | #include <stdio.h> #include <stdafx.h> #include <windows.h> #include <winsock2.h> #include <stdlib.h> #include <conio.h> #define DEFAULT_BUFFER 4096 #define DEFAULT_COUNT 5 #define DEFAULT_MESSAGE "This is a test message." char szServer[128], // Server to connect to szMessage[1024]; // Message to send to sever int iPort; // Port on server to connect to DWORD dwCount = DEFAULT_COUNT; // Number of times to send message BOOL bSendOnly = FALSE; // Send data only; don't receive BOOL bInterface = FALSE; // Listen on the specified interface BOOL bRecvOnly = FALSE; BOOL bWork = TRUE; //server working is TRUE char szAddress[128]; // Interface to listen for clients on DWORD WINAPI ClientThread(LPVOID lpParam) { SOCKET sock=(SOCKET)lpParam; char szBuff[DEFAULT_BUFFER]; int ret, nLeft, idx;
while(1) { // Perform a blocking recv() call // ret = recv(sock, szBuff, DEFAULT_BUFFER, 0); if (ret == 0) // Graceful close break; else if (ret == SOCKET_ERROR) { printf("recv() failed: %d\n", WSAGetLastError()); break; } szBuff[ret] = '\0'; printf("RECV: '%s'\n", szBuff); // // If we selected to echo the data back, do it // if (!bRecvOnly) { nLeft = ret; idx = 0; // // Make sure we write all the data // while(nLeft > 0) { ret = send(sock, &szBuff[idx], nLeft, 0); if (ret == 0) break; else if (ret == SOCKET_ERROR) { printf("send() failed: %d\n", WSAGetLastError()); break; } nLeft -= ret; idx += ret; } } } return 0; }
int server(void) { WSADATA wsd; SOCKET sListen, sClient; int iAddrSize; HANDLE hThread; DWORD dwThreadId; struct sockaddr_in local, client;
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("Failed to load Winsock!\n"); return 1; } // Create our listening socket // sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP); if (sListen == SOCKET_ERROR) { printf("socket() failed: %d\n", WSAGetLastError()); return 1; } // Select the local interface and bind to it // if (bInterface) { local.sin_addr.s_addr = inet_addr(szAddress); } else local.sin_addr.s_addr = htonl(INADDR_ANY); local.sin_family = AF_INET; local.sin_port = htons(iPort);
if (bind(sListen, (struct sockaddr *)&local, sizeof(local)) == SOCKET_ERROR) { printf("bind() failed: %d\n", WSAGetLastError()); return 1; } listen(sListen, 8); // // In a continous loop, wait for incoming clients. Once one // is detected, create a thread and pass the handle off to it. // printf("Server started Normally. IP address is %s, port is %d\n",szAddress, iPort); printf("For STOP press X\n"); while (bWork) { iAddrSize = sizeof(client); sClient = accept(sListen, (struct sockaddr *)&client, &iAddrSize); if (sClient == INVALID_SOCKET) { printf("accept() failed: %d\n", WSAGetLastError()); break; } printf("Accepted client: %s:%d\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
hThread = CreateThread(NULL, 0, ClientThread, (LPVOID)sClient, 0, &dwThreadId); if (hThread == NULL) { printf("CreateThread() failed: %d\n", GetLastError()); break; } CloseHandle(hThread); } closesocket(sListen); WSACleanup(); return 0; } int client(void) { WSADATA wsd; SOCKET sClient; char szBuffer[DEFAULT_BUFFER]; int ret, i; struct sockaddr_in server; struct hostent *host = NULL;
// Parse the command line and load Winsock // if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) { printf("Failed to load Winsock library!\n"); return 1; } strcpy(szMessage, DEFAULT_MESSAGE); // // Create the socket, and attempt to connect to the server // sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sClient == INVALID_SOCKET) { printf("socket() failed: %d\n", WSAGetLastError()); return 1; } server.sin_family = AF_INET; server.sin_port = htons(iPort); server.sin_addr.s_addr = inet_addr(szServer); // // If the supplied server address wasn't in the form // "aaa.bbb.ccc.ddd" it's a hostname, so try to resolve it // printf("Connection to IP %s PORT %d\n", szAddress, iPort); if (server.sin_addr.s_addr == INADDR_NONE) { host = gethostbyname(szServer); if (host == NULL) { printf("Unable to resolve server: %s\n", szServer); return 1; } CopyMemory(&server.sin_addr, host->h_addr_list[0], host->h_length); } printf("Resolving server succsessful.\n"); if (connect(sClient, (struct sockaddr *)&server,sizeof(server)) == SOCKET_ERROR) { printf("connect() failed: %d\n", WSAGetLastError()); return 1; } printf("COnnected.\n"); // Send and receive data // for(i = 0; i < dwCount; i++) { ret = send(sClient, szMessage, strlen(szMessage), 0); if (ret == 0) break; else if (ret == SOCKET_ERROR) { printf("send() failed: %d\n", WSAGetLastError()); break; } printf("Send %d bytes\n", ret); if (!bSendOnly) { ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0); if (ret == 0) // Graceful close break; else if (ret == SOCKET_ERROR) { printf("recv() failed: %d\n", WSAGetLastError()); break; } szBuffer[ret] = '\0'; printf("RECV [%d bytes]: '%s'\n", ret, szBuffer); } } closesocket(sClient);
WSACleanup(); return 0; }
void main(int argc, char** argv) { if (argc==4) { iPort = atoi(argv[3]); strcpy_s(szAddress, argv[2]); if (argv[1][0]=='s') server(); else client(); } else printf("Check parameter string. Press any key for Exit.\n"); _getch(); }
|
если кто захочет помоч разобраться, правила запуска: 1 параметр ком строки s (sever) c (client) 2 параметр ком строки ip адрес... например 192.168.1.2 3 параметр ком строки порт, например 5555. Пример ком строки: p.exe s 192.168.1.2 5555 Заранее благодарен  Кому лень компилить прикрепляю экзешник
Присоединённый файл ( Кол-во скачиваний: 4 )
client_server.rar 8,97 Kb
|