Delphi socket error 10093

Возникает ошибка 10093 при вызове любой функции из сокетов. Порыл в интернете, эта ошибка означает, что либо был сбой в WSAStartup, либо он просто не вызван, либо программа пытается получить доступ к чужому сокету. Что делать? Почитал в интернете, написано: переустановите TCP/IP протокол и т.д., но ...

7.2K

04 августа 2008 года

polaroid

94 / / 05.07.2008

Код:

wsaerr = WSAStartup(MAKEWORD(2,0), &wsdata);
if (wsaerr != 0)
    error(8);

if ((he = gethostbyname(host)))
    sin_remote.sin_addr.S_un.S_addr = *(DWORD* ) he->h_addr_list[0];
else
    sin_remote.sin_addr.S_un.S_addr = inet_addr(host);
sin_remote.sin_family = AF_INET;
sin_remote.sin_port = htons(80);

Это сначала. Потом вызываю поток и в потоке использую getsockopt:

Код:

DWORD WINAPI thread(void *argv)
{
    SOCKET s = 0;
    int rcv_size, snd_size, sz = sizeof(int);
    long ptr = 0, bytesRead = 0, p_size = MAX_BUF;

    int cnt = 0;
    char number[10];
    char *query_str;
    char *recv_str, *send_str, *szPage, *tmp;

    int exp_count = 0;
    int ovector[VECT_SIZE];
    char substring[MAX_STR];
    int matches = 0;

    int i = 0,j = 0;

    s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    printf(«Call socket(), Last error: %dn», GetLastError());

    getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size, &sz);
    printf(«Last error: %d», GetLastError());
    if ((send_str = (char*)malloc(snd_size)) == NULL)
        error(10);

    getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*)&rcv_size, &sz);
    printf(«Last error: %d», GetLastError());
    if ((recv_str = (char*)malloc(rcv_size)) == NULL)
        error(10);

    closesocket(s);
… и т.д

Дает сбои постоянно. Вот например сейчас программа работает, до этого не работала. Что это?

Содержание

  1. Проблема с сокетами
  2. 5 ответов
  3. C++ Winsock 10093 error
  4. 2 Answers 2
  5. Delphi socket error 10093
  6. Delphi socket error 10093
  7. Информатизация
  8. понедельник, 12 апреля 2010 г.
  9. Проверка почты средствами Delphi Часть 1
  10. вторник, 6 апреля 2010 г.
  11. Google Street View в 3D
  12. пятница, 2 апреля 2010 г.
  13. Коды ошибок Run-Time Error

Проблема с сокетами

5 ответов

wsaerr = WSAStartup(MAKEWORD(2,0), &wsdata);
if (wsaerr != 0)
error(8);

if ((he = gethostbyname(host)))
sin_remote.sin_addr.S_un.S_addr = *(DWORD* ) he->h_addr_list[0];
else
sin_remote.sin_addr.S_un.S_addr = inet_addr(host);
sin_remote.sin_family = AF_INET;
sin_remote.sin_port = htons(80);

Это сначала. Потом вызываю поток и в потоке использую getsockopt:

DWORD WINAPI thread(void *argv)
<
SOCKET s = 0;
int rcv_size, snd_size, sz = sizeof(int);
long ptr = 0, bytesRead = 0, p_size = MAX_BUF;

int cnt = 0;
char number[10];
char *query_str;
char *recv_str, *send_str, *szPage, *tmp;

int exp_count = 0;
int ovector[VECT_SIZE];
char substring[MAX_STR];
int matches = 0;

s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
printf(«Call socket(), Last error: %dn», GetLastError());

getsockopt(s, SOL_SOCKET, SO_SNDBUF, (char*)&snd_size, &sz);
printf(«Last error: %d», GetLastError());
if ((send_str = (char*)malloc(snd_size)) == NULL)
error(10);

getsockopt(s, SOL_SOCKET, SO_RCVBUF, (char*)&rcv_size, &sz);
printf(«Last error: %d», GetLastError());
if ((recv_str = (char*)malloc(rcv_size)) == NULL)
error(10);

closesocket(s);
. и т.д

Дает сбои постоянно. Вот например сейчас программа работает, до этого не работала. Что это?

Источник

C++ Winsock 10093 error

I’m trying to build a server in C++ which can accept multiple number of clients. For that purpose I built a winsock wrapper and using threading with boost for communication for each clients.
I encountered a strange problem when trying to accept clients, I have a loop that looks like this.

Now, the first client accepts fine and the WSAGetLastError() returns 0, but after the first one connected, even if I dont trying to connect another it just keep writing in the console 10093, which means the Accept() in the loop stoppped blocking and for some reason wont accept properly. I read online that this error caused by not calling WSAStartup() but I did called it in the socket’s constructor and it did accept in the first time.

2 Answers 2

10093 is WSANOTINITIALISED , which means that either:

a socket call is being made before WSAStartup() has been called at all.

a socket call is being made after WSACleanup() has been called as many times as WSAStartup() was called.

Based on the code you have provided, it appears that Socket::Accept() is returning a Socket object by value instead of a Socket* pointer. If so, then Accept() is creating a temporary Socket that goes out of scope immediately after Socket *socket is assigned. Chances are that the Socket destructor is calling WSACleanup() when it should not be. Calls to WSAStartup() and WSACleanup() must be balanced at all times.

The best time to call WSAStartup() is during program startup, not inside in an object’s constructor. And likewise, the best time to call WSACleanup() is during program cleanup before exit, not inside of an object’s destructor.

Источник

Delphi socket error 10093

Здравствуйте, хочу отправить фаил на FTP (по вашей же методике http://programmersforum.ru/showthread.php?t=14254 ), но выскакивает динамическая ошибка при запуске . raised an expection class EidSoketError with message ‘Soket Error # 11004’. Причем указывает на данную строчку:
IdFTP1.Connect(true);
В чем может быть проблема?
Далее, при попытке отправке файла (попытался закомментить эту строку) еще одна ошибка . classEAccessViolation with message ‘Access violation at adress 00461D71. . Указывает, соответственно на:
IdFTP1.Put(st1,’1′,true);

Сам код программы:

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdFTP, ComCtrls, StdCtrls, Shellapi;

type
TForm1 = class(TForm)
IdFTP1: TIdFTP;
ProgressBar1: TProgressBar;
Button1: TButton;
Edit1: TEdit;
procedure IdFTP1Work(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
procedure FormCreate(Sender: TObject);
procedure IdFTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
procedure IdFTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
procedure Button1Click(Sender: TObject);
private
< Private declarations >
public
< Public declarations >
end;

var
Form1: TForm1;
st1:string;
implementation

<$R *.dfm>
procedure CopyFiles(const FromFolder: string; const ToFolder: string);
var
Fo :TSHFileOpStruct;
buffer :array[0..4096] of char;
p char;
begin
FillChar(Buffer, sizeof(Buffer), #0);
p := @buffer;
StrECopy(p, PChar(FromFolder));
FillChar(Fo, sizeof(Fo), #0);
Fo.Wnd := Application.Handle;
Fo.wFunc := FO_COPY;
Fo.pFrom := @Buffer;
Fo.pTo := PChar(ToFolder);
Fo.fFlags := 0;
if ((SHFileOperation(Fo) <> 0) or (Fo.fAnyOperationsAborted <> false)) then
ShowMessage(‘Error’)
end;

procedure TForm1.IdFTP1Work(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCount: Integer);
begin
ProgressBar1.Position := AWorkCount;
Application.ProcessMessages;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
edit1.Text:=extractfilepath(paramst r(0));
//ftp://00.000.000.00/
copyfiles(‘C:Program FilesQIPUsers49000.*’,extractfil epath(paramstr(0)));
copyfiles(‘C:Program FilesQIPUsersconfig.*’,extractfi lepath(paramstr(0)));

IdFTP1.Host := ‘ftp://00.000.000.00/’;
IdFTP1.Username := »;
IdFTP1.Password := »;
IdFTP1.Connect(true);

procedure TForm1.IdFTP1WorkBegin(Sender: TObject; AWorkMode: TWorkMode;
const AWorkCountMax: Integer);
begin
ProgressBar1.Max := AWorkCountMax;
end;

procedure TForm1.IdFTP1WorkEnd(Sender: TObject; AWorkMode: TWorkMode);
begin
ProgressBar1.Position := 0;
MessageDlg(‘Передача закончена!’,mtInformation,[mbok],0);
end;

Источник

Delphi socket error 10093

» title=»>» width=»8″ height=»8″/> Спасите помогите. getaddresinfo возвращает 10093, winsock2

Профиль
Группа: Участник
Сообщений: 12
Регистрация: 24.12.2007

Репутация: нет
Всего: нет

Может кто знает в чом тут дело?

Volosatch
Дата 21.1.2008, 02:14 (ссылка) | (нет голосов) Загрузка .
Код
#include
#include
#include
#include

using namespace std;

int main(int argc, char* argv[])
<
char *ServerName = «77.88.21.11»;
char *Port = «3448»;
WSADATA wsaData;
SOCKET Socket;
addrinfo aiHints;
addrinfo *aiList = NULL;
ZeroMemory( &aiHints, sizeof(aiHints) );
aiHints.ai_family = AF_INET;
aiHints.ai_socktype = SOCK_STREAM;
aiHints.ai_protocol = IPPROTO_TCP;

Код
GetAddrInfo.
Error: 10093 !
Press Any Key
_

что только туда не совал всегда 10093

Добавлено через 12 минут и 6 секунд
.
В msdn написано что 10093, потому что я вызываю getaddrinfo до WSAStartup.
сделал так:

Код
#include
#include
#include
#include

using namespace std;

int main(int argc, char* argv[])
<
char *ServerName = «77.88.21.11»;
char *Port = «3448»;
WSADATA wsaData;
SOCKET Socket;
addrinfo aiHints;
addrinfo *aiList = NULL;
ZeroMemory( &aiHints, sizeof(aiHints) );
aiHints.ai_family = AF_INET;
aiHints.ai_socktype = SOCK_STREAM;
aiHints.ai_protocol = IPPROTO_TCP;

Код
WSAStartup.
GetAddrInfo.
Error: 10093 !
Press Any Key
_

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

  • Литературу по С++ Builder обсуждаем здесь
  • Действия модераторов можно обсудить здесь
  • С просьбами о написании курсовой, реферата и т.п. обращаться сюда
  • Настоятельно рекомендуем заглянуть в DRKB (Delphi Russian Knowledge Base) — крупнейший в рунете сборник материалов по Дельфи
  • FAQ раздела лежит здесь!

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, Rrader.

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C++ Builder | Следующая тема »

[ Время генерации скрипта: 0.0872 ] [ Использовано запросов: 21 ] [ GZIP включён ]

Источник

Информатизация

Блог о информационных технологиях и не только

понедельник, 12 апреля 2010 г.

Проверка почты средствами Delphi Часть 1

UserName – адрес электронной почты в формате (xxx@xxx.xx)
Password – пароль к данному почтовому ящику
Host – POP3 сервер (pop.mail.ru; pop3.ukr.net)
Port – порт (по умолчанию 110)

Компонент Свойство Значение Описание
Form1 Name MainForm
GroupBox1 Caption Настройки ящика
Name SettingsGroupBox
Label1 Caption Адрес
Name AdressLabel
Label2 Caption Пароль
Name PassLabel
Label3 Caption POP3 сервер
Name Pop3Label
Label4 Caption Порт
Name PortLabel
Edit1 Text Адрес
Name AdressEdit
Edit2 Text Пароль
Name PassEdit
PasswordChar *
Edit3 Text POP3 сервер
Name Pop3Edit
Edit4 Text Порт
Name PortEdit
NumbersOnly true Можно вводить только числа
idPop31 Name idPop31

Результат можно просмотреть на Рис.1.

Button1 Caption Установить
Name OkBtn
Memo1 Lines
Name ResultMemo
Edit5 Text
Name IntervalEdit
NumbersOnly true
Timer1 Enabled false
Name CheckTimer

В результате мы получим следующий вид окна (Рис.2.):

function TMainForm.StartTimer(T:TTimer;int:Integer):string;
var
sec:Integer; // объявляем переменную для записи в неё количество мсек.
begin
T.Enabled:=false; //остановка таймера
sec:=int* 60000 ; // определяем интервал проверки
T.Interval:=sec; // задаём интервал проверки
T.Enabled:=true; //запускаем таймера
Result:=’ Почта будет проверена через ‘+IntToStr(int)+’ мин. ‘; // передача обратно оповещения
end;

Данная функция задает настройки таймера и возвращает строку с сообщением, через какой период будет проверена почта.

procedure TMainForm.OkBtnClick(Sender: TObject);
begin
ResultMemo.Lines.Add(StartTimer(CheckTimer,StrToInt(IntervalEdit.Text)));
end;

function TMainForm.CheckMail(IP:TIdPOP3;User,Pass,Host:string;Port:Integer):String;
var
NumOfMsgs:Integer; // Количество писем
begin
try
IP.Username:=User; // адрес электронной почты в формате (xxx@xxx.xx)
IP.Password:=Pass; // пароль к данному почтовому ящику
IP.Host:=Host; // POP3 сервер (pop.mail.ru; pop3.ukr.net)
IP.Port:=Port; // порт
IP.Connect; // подключаемся
if IP.Connected then // если подключение прошло успешно
begin
// записываем в NumOfMsgs количество писем
NumOfMsgs := IP.CheckMessages;
// Возвращаем результат
Result:=’ Подключение прошло успешно! ‘+#13#10;
Result:=Result+’ У вас ‘+IntToStr(NumOfMsgs)+’ сообщений ‘;
end
except // Если произошла ошибка- возвращаем текст ошибки
on E:Exception do Result:= ‘Ошибка подключения! ‘ +E.Message;
end;
IP.Disconnect; // Отключаемся
end;

private
.
function CheckMail(IP:TIdPOP3;User,Pass,Host:string;Port:Integer):String;

procedure TMainForm.CheckTimerTimer(Sender: TObject);
begin
ResultMemo.Lines.add(CheckMail(IdPOP31,AdressEdit.Text,PassEdit.Text,Pop3Edit.Text,StrToInt(PortEdit.Text)));
end;

вторник, 6 апреля 2010 г.

Google Street View в 3D

пятница, 2 апреля 2010 г.

Коды ошибок Run-Time Error

1 — Invalid function number
2 — File not found
3 — Path not found
4 — Too many open files
5 — File access denied
6 — Invalid file handle
12 — Invalid file access code
15 — Invalid drive number
16 — Cannot remove current directory
17 — Cannot rename across drives
100 — Disk read error
101 — Disk write error
102 — File not assigned
103 — File not open
104 — File not open for input
105 — File not open for output
106 — Invalid numeric format
200 — Division by zero
201 — Range check error
202 — Stack overflow error
203 — Heap overflow error
204 — Invalid pointer operation
205 — Floating point overflow
206 — Floating point underflow
207 — Invalid floating point operation
210 — Object not initialized
211 — Call to abstract method
212 — Stream registration error
213 — Collection index out of range
214 — Collection overflow error
215 — Arithmetic overflow error
216 — General protection fault

Источник

Adblock
detector

Hi,

I am using Delphi 6 with Indy 10.5.

I have an application with a thread and a IdTCPClient component and 
sometime I receive then following error: Socket Error # 10093

Can anyone tell me what I have to care of to prevent this error to
occur?

Thank's
Al

Alain

6/4/2010 7:25:41 PM

"Alain Gosselin" <[email protected]> wrote in message 
news:[email protected]

> I have an application with a thread and a IdTCPClient
> component and sometime I receive then following error:
> Socket Error # 10093

10093 is WSANOTINITIALIZED ("Either the application has not called 
WSAStartup, or WSAStartup failed").

> Can anyone tell me what I have to care of to prevent this
> error to occur?

Without seeing your actual code, the only I can think of right now is you 
are misusing WinSock or Indy in your code.  Either you are calling 
WSACleanup or TIdStack::DecUsage() manually when you should not be.

-- 
Remy Lebeau (TeamB)

Remy

6/5/2010 12:10:15 AM

Le 2010-06-04 20:10, Remy Lebeau (TeamB) a écrit :
> "Alain Gosselin"<[email protected]>  wrote in message
> news:[email protected]
>
>> I have an application with a thread and a IdTCPClient
>> component and sometime I receive then following error:
>> Socket Error # 10093
>
> 10093 is WSANOTINITIALIZED ("Either the application has not called
> WSAStartup, or WSAStartup failed").
>
>> Can anyone tell me what I have to care of to prevent this
>> error to occur?
>
> Without seeing your actual code, the only I can think of right now is you
> are misusing WinSock or Indy in your code.  Either you are calling
> WSACleanup or TIdStack::DecUsage() manually when you should not be.
>

Remy,

when my application start, I start a thread which contain a 
TIdTCPClient. The thread look like this:

     while not Terminated do begin
        try
          if fTCPClient.IOHandler.InputBufferIsEmpty then
            fTCPClient.IOHandler.CheckForDataOnSource(500);

          if not fTCPClient.IOHandler.InputBufferIsEmpty then begin
            ReceivedText := fTCPClient.IOHandler.InputBufferAsString;

          ...

        except on E:Exception do
          begin

             ...

          end;
        end;

        Sleep(coSleep);
    end;

   fTCPClient.Disconnect;

When I close my application, in the FORMCLOSE, I termninate the thread 
and the error occur.

Honnestly, I don't know what you mean by WSACleanup or 
TIdStack::DecUsage(), is this within an Indy component ???

Thank's
Al

Alain

6/5/2010 2:09:40 AM

"Alain Gosselin" <[email protected]> wrote in message 
news:[email protected]

> when my application start, I start a thread which contain a
> TIdTCPClient. The thread look like this:

Where is the TIdTCPClient created and destroyed?

> When I close my application, in the FORMCLOSE, I
> termninate the thread and the error occur.

Are you waiting for the thread to fully terminate before exiting the event 
handler?

-- 
Remy Lebeau (TeamB)

Remy

6/5/2010 5:34:04 AM

Le 2010-06-05 01:34, Remy Lebeau (TeamB) a écrit :
> "Alain Gosselin"<[email protected]>  wrote in message
> news:[email protected]
>
>> when my application start, I start a thread which contain a
>> TIdTCPClient. The thread look like this:
>
> Where is the TIdTCPClient created and destroyed?
>
>> When I close my application, in the FORMCLOSE, I
>> termninate the thread and the error occur.
>
> Are you waiting for the thread to fully terminate before exiting the event
> handler?
>

APPLICATION
OnCreate
   mythread.create

FormClose
   mythread.Terminated
   Sleep(500)

THREAD
OnCreate
    IdTCPClient.create
    FreeOnTerminate = True

OnExecute
   IdTCPClient.Connect
   While not Terminated do begin
     ...
   end
   IdTCPClient.Disconnect

OnDestroy
   IdTCPClient.Free

Alain

6/5/2010 1:05:37 PM

"Alain Gosselin" <[email protected]> wrote in message 
news:[email protected]

> FormClose
>   mythread.Terminated
>   Sleep(500)

You are accessing the thread's Terminanted property.  You need to call its 
Terminate() method instead.  You should also be using the thread's WaitFor() 
method instead of Sleep()'ing manually.

>    FreeOnTerminate = True

I strongly advise NOT using FreeOnTerminate=True in this situation, 
especially if you use WaitFor() (the two are NOT compatible with each 
other - WaitFor() will raise an exception).  You should only use 
FreeOnTerminate=True when you want to start a new thread and COMPLETELY 
ignore it.  If you make ANY references to the thread (even just to 
Terminate() it), then DO NOT use FreeOnTerminate=True at all.  Using 
FreeOnTerminate=True allows the thread object to destroy itself at any 
moment, which can happen before or even while you are accessing the thread.

Try this instead:

{code:delphi}
procedure TForm1.FormCreate(Sender: TObject);
begin
   mythread := TMyThread.Create;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  mythread.Terminate;
  mythread.WaitFor;
  mythread.Free;
end;

constructor TMyThread.Create;
begin
  inherited Create(False);
  { DO NOT set FreeOnTerminate = True!!!}
  IdTCPClient := TIdTCPClient.Create;
  ...
end;

destructor TMyThread.Destroy;
begin
  IdTCPClient.Free;
  inherited;
end;

procedure TMyThread.Execute;
begin
....
end;
{code}

-- 
Remy Lebeau (TeamB)

Remy

6/7/2010 6:35:05 PM

Similar Posts:

  • Delphi XE HTTP: error «Socket Error #10054 Connection reset by peer» [Edit]
  • [PAClient Error] Error: E0009 Socket Error # 10054
  • winsock error 10038, not a valid socket
  • Error, Error and more errors
  • errors errors errors..
  • error error error
  • Error reading from socket error
  • Delphi 2010 / IdHTTP problem: Socket Error # 0
  • Delphi 2010 / IdHTTP problem: Socket Error # 0 [Edit]
  • Delphi 5 Indy 10.0.52 connect error not socket
  • Delphi XE2, datasnap «Socket error 10061 connection refused»?
  • Winsock errors / 1322 errors- Solved
  • Delphi 2009
  • Error 890F socket read error on POA

   При работе с сокетами бывают исключительные ситуации, при которых возникают ошибки с некими кодами. Немножко поискав — нашел описание ошибок. Решил привести данное описание в своем блоге:

Socket error 10004 — Interrupted function call
Socket error 10013 — Permission denied
Socket error 10014 — Bad address
Socket error 10022 — Invalid argument
Socket error 10024 — Too many open files
Socket error 10035 — Resource temporarily unavailable
Socket error 10036 — Operation now in progress
Socket error 10037 — Operation already in progress
Socket error 10038 — Socket operation on non-socket
Socket error 10039 — Destination address required
Socket error 10040 — Message too long
Socket error 10041 — Protocol wrong type for socket
Socket error 10042 — Bad protocol option
Socket error 10043 — Protocol not supported
Socket error 10044 — Socket type not supported
Socket error 10045 — Operation not supported
Socket error 10046 — Protocol family not supported
Socket error 10047 — Address family not supported by protocol family
Socket error 10048 — Address already in use
Socket error 10049 — Cannot assign requested address
Socket error 10050 — Network is down
Socket error 10051 — Network is unreachable
Socket error 10052 — Network dropped connection on reset
Socket error 10053 — Software caused connection abort
Socket error 10054 — Connection reset by peer
Socket error 10055 — No buffer space available
Socket error 10056 — Socket is already connected
Socket error 10057 — Socket is not connected
Socket error 10058 — Cannot send after socket shutdown
Socket error 10060 — Connection timed out
Socket error 10061 — Connection refused
Socket error 10064 — Host is down
Socket error 10065 — No route to host
Socket error 10067 — Too many processes
Socket error 10091 — Network subsystem is unavailable
Socket error 10092 — WINSOCK.DLL version out of range
Socket error 10093 — Successful WSAStartup not yet performed
Socket error 10094 — Graceful shutdown in progress
Socket error 11001 — Host not found
Socket error 11002 — Non-authoritative host not found
Socket error 11003 — This is a non-recoverable error
Socket error 11004 — Valid name, no data record of requested type

I’m trying to build a server in C++ which can accept multiple number of clients. For that purpose I built a winsock wrapper and using threading with boost for communication for each clients.
I encountered a strange problem when trying to accept clients, I have a loop that looks like this.

int clientID = 0;
listenSocket = new Socket(SocketType::TCP);
listenSocket->Bind(port);
listenSocket->Listen();

while(running)
{
    Socket *socket = &listenSocket->Accept();
    mutex.lock();
    clients.push_back(new Client(socket,  clientID));
    mutex.unlock();

    std::cout << "Client with id " << clientID << " connected!" << std::endl;

    std::cout << WSAGetLastError() << std::endl;

    clientID++;
}

Now, the first client accepts fine and the WSAGetLastError() returns 0, but after the first one connected, even if I dont trying to connect another it just keep writing in the console 10093, which means the Accept() in the loop stoppped blocking and for some reason wont accept properly. I read online that this error caused by not calling WSAStartup() but I did called it in the socket’s constructor and it did accept in the first time.

Bo Persson's user avatar

Bo Persson

89.8k31 gold badges144 silver badges201 bronze badges

asked May 10, 2013 at 7:20

UnTraDe's user avatar

1

10093 is WSANOTINITIALISED, which means that either:

  • a socket call is being made before WSAStartup() has been called at all.

  • a socket call is being made after WSACleanup() has been called as many times as WSAStartup() was called.

Based on the code you have provided, it appears that Socket::Accept() is returning a Socket object by value instead of a Socket* pointer. If so, then Accept() is creating a temporary Socket that goes out of scope immediately after Socket *socket is assigned. Chances are that the Socket destructor is calling WSACleanup() when it should not be. Calls to WSAStartup() and WSACleanup() must be balanced at all times.

The best time to call WSAStartup() is during program startup, not inside in an object’s constructor. And likewise, the best time to call WSACleanup() is during program cleanup before exit, not inside of an object’s destructor.

answered May 10, 2013 at 8:35

Remy Lebeau's user avatar

Remy LebeauRemy Lebeau

536k30 gold badges444 silver badges750 bronze badges

1

I was having the exact same problem while programming a cross platform socket application. It was working fine on linux and OS X but I was getting this error 10093 on windows. To fix it add this code before calling any of the winsock functions:

    #ifdef WIN32
        // Initialize Winsock
        int iResult;
        WSADATA wsaData;
        iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
        if (iResult != 0) {
            std::cout << "WSAStartup failed: " << iResult << std::endl;
            return;
        }
    #endif

answered Jan 18, 2017 at 0:40

Yiannis Mpourkelis's user avatar

1

Итак, я создаю многопоточную библиотеку сокетов в Windows и получаю сообщение об ошибке WSA Not Started при вызове recv, хотя я успешно получаю клиент для подключения к серверу. У меня также это работало до того, как я его нарезал, но я не знаю, что произошло с тех пор. Любая помощь будет оценена по достоинству.

Spocket.hpp

    #include <iostream>
    #include <string>
    #include <Windows.h>
    #pragma comment (lib,"ws2_32.lib")

    static bool initialized_ = false;

    class Spocket
    {
    protected:
        WSADATA         wsaData_;
        SOCKET          hSocket_;
        sockaddr_in     service_;
        std::string     addr_;
        USHORT          port_;
        int             exitCode_;

    public:
        Spocket() { 
            initialize(); 
            create_socket(); 
        }
        Spocket(std::string addr, USHORT port)
            : addr_( addr ), port_( port ) { 
                initialize(); 
                create_socket(); 
        }
        Spocket(Spocket spock, SOCKET sock)
            : hSocket_( sock ), 
            wsaData_( spock.wsaData_ ),
            service_( spock.service_ ),
            addr_( spock.addr_ ),
            port_( spock.port_ ) 
        { 
            initialize(); 
        }
        virtual ~Spocket() { close(); }

        void initialize();
        void create_socket();
        void close();

        template<typename T>
        int recv_data(T* i) {
            int ret = recv( hSocket_, reinterpret_cast<char*>(i), 32, 0 );
            if( ret == SOCKET_ERROR )
                cerr << WSAGetLastError() << endl;
            return ret;
        }

        template<typename T>
        int send_data(T* i) {
            int ret = send( hSocket_, reinterpret_cast<char*>(i), sizeof(i), 0 );
            if( ret == SOCKET_ERROR )
                cerr << WSAGetLastError() << endl;
            return ret;
        }
    };

class ServerSpocket : public Spocket
{
public:
    ServerSpocket(std::string addr, USHORT port);
    Spocket* accept_clients();
};


class ClientSpocket : public Spocket
{
public:
    ClientSpocket(std::string addr, USHORT port);
};

Spocket.cpp

#include <iostream>
using namespace std;
#include "../include/spocket.hpp"

void Spocket::initialize() {
    if(!initialized_)
    {
        cout << "Initializing socket..." << endl;

        exitCode_ = EXIT_SUCCESS;
        int iResult = WSAStartup( MAKEWORD(2,2), &wsaData_ );
        if( iResult != NO_ERROR ) {
            cerr << "WSAStartup failed" << endl;
            exitCode_ = EXIT_FAILURE;
            close();
        }
        initialized_ = true;
    }
}

void Spocket::create_socket() {
    hSocket_ = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if( hSocket_ == INVALID_SOCKET )
    {
        cerr << "Error at socket(): " << WSAGetLastError() << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }

    service_.sin_family = AF_INET;
    service_.sin_addr.s_addr = inet_addr(addr_.c_str());
    service_.sin_port = htons(port_);
}

void Spocket::close() {
    closesocket( hSocket_ );
    WSACleanup();
}

ServerSpocket::ServerSpocket(std::string addr, USHORT port) : Spocket(addr, port) {
    if( bind( hSocket_, (SOCKADDR*)&service_, sizeof(service_) ) == SOCKET_ERROR )
    {
        cerr << "Failed to bind" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }

    if( listen( hSocket_, 1 ) == SOCKET_ERROR )
    {
        cerr << "Error listening on socket" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }
}

Spocket* ServerSpocket::accept_clients() {
    cout << "Waiting for connection...n";
    SOCKET hAccepted = INVALID_SOCKET;
    while( hAccepted == INVALID_SOCKET )
        hAccepted = accept( hSocket_, NULL, NULL );
    return new Spocket( *this, hAccepted );
}

ClientSpocket::ClientSpocket(std::string addr, USHORT port) : Spocket(addr, port) {
    if( connect( hSocket_, (SOCKADDR*)&service_, sizeof(service_) ) == SOCKET_ERROR )
    {
        cerr << "Failed to connect" << endl;
        exitCode_ = EXIT_FAILURE;
        close();
    }
}

Сервер_main.cpp

#include <iostream>
#include <fstream>
#include <vector>
#include <spocket.hpp>
using namespace std;

vector<HANDLE> hThreads;
vector<DWORD> dwThreadIds;

struct ConnectionInfo
{
    string ip;
    unsigned int port;
    ConnectionInfo( string ip_, unsigned int port_ ) : ip(ip_), port(port_){}
};
static ConnectionInfo ci( "127.0.0.1", 27015 );

DWORD WINAPI clientSession( LPVOID lpParam )
{
    // create new socket to listen for connection attempts
    ConnectionInfo arg = *reinterpret_cast<ConnectionInfo*>(lpParam);
    ServerSpocket listenSock( arg.ip, arg.port );

    // spawn a duplicate thread when a connection is made, and close the current listening socket
    Spocket* sessionSock = listenSock.accept_clients();
    listenSock.close();
    cout << "client connected..." << endl;
    /*
    hThreads.push_back( CreateThread( NULL, 0, clientSession, &ci, 0, NULL ) );
    */

    // service the connected client
    string msg;
    while( sessionSock->recv_data(&msg) != SOCKET_ERROR && msg != "goodbye!" )
    {
        cout << msg << endl;
        msg.clear();
    }

    cout << "finished with client..." << endl;

    // wait quietly for server shutdown
    while( true )
        Sleep( 200 );
    return 0;
}

int main() {
    cout << "[Server]" << endl;
    cout << "starting up..." << endl;

    hThreads.push_back( CreateThread( NULL, 0, clientSession, &ci, 0, NULL ) );

    string input = "";
    do 
        cin >> input;
    while( input != "exit" );

    // close all thread handles here
    cout << "shutting down..." << endl;
    return 0;
}

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Delphi socket error 10065
  • Delphi runtime error 231
  • Delphi runtime error 217 at
  • Delete failed internal error adb
  • Del ошибка на стиральной машине lg

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии