Содержание
- Operating system call recv failed (error no. 10054)
- How to analyze network disconnections shown in system log (BC transaction SM21) ?
- Recv failed with error 10054
- Recv failed with error 10054
- Правила форума
- Operating system call recv failed (error no. 10054)
- Кто сейчас на конференции
Operating system call recv failed (error no. 10054)
How to analyze network disconnections shown in system log (BC transaction SM21) ?
System log (transaction SM21) shows network disconnections, e.g.
- Q04 Connection to user 2642 (EXTRACAO), terminal 38 (iguacucp125) lost
- Delete session 001 after error 061
- Operating system call recv failed (error no. 10054)
First at all, consider that a «network disconnection» in the system log (transaction SM21) or in a developer trace is not always meaningful; a typical case is an operating system 10061 error while trying to connect e.g. to the gateway of an SAP system that crashed; obviously, while trying to contact the sapgwXX service of the remote host, the connection cannot be established as the gateway is not running there. In case that still it makes sense to analyze the disconnection, there are several possibilities to analyze the errors:
SAP software: SAPgui and kernel
- Make sure that you are using the latest SAPGUI available.
- Make sure that your current SAP kernel is up-to-date (at least not older than half a year) in your SAP application servers.
- This is the starting point to eliminate that error. There are other possible causes that are to be checked if the issue persists after updating to the latest kernel and GUI patches, namely:
- A user with authorization for transaction SM04 can delete a session of any user; this will generate that message in the syslog and tracefiles.
- If a user is already logged in the system and he logs again with the same user, then he will get a pop up window with three options
- Continue with this logon and end any other logon (then his previous session in the system will be ended, and the information message «Delete session XXX after error 061» will be issued)
- Continue this log on without ending other logo
- Terminate this logon
- Another possibility are problems with the SAPGUI. In this case you should see some error messages after activating the frontend-trace.
Operating System support level: workstations and server(s)
Ensure that your systems are patched to the highest support pack, as well as the network card drivers, etc.
Check your hostname configuration (‘hosts’ files in the workstations, etc.).
Parametrization of SAP system
Sometimes disconnections are not a failure, but a feature offered by the SAP software to avoid the waste of resources due to disconnections caused by users closing the SAPgui without the proper log off, etc. The lines below explain how this mechanism works.
The kernel regularly checks whether a session is still in use and any session that is no longer in use is removed; the check is very simple: if the frontend has not sent any data to the application server for «rdisp/keepalive» seconds, the application server sends a short «ping» message to the frontend. The frontend should answer within the next 40 seconds with «pong», otherwise the application server assumes that the link is dead and releases all resources to the corresponding user. An error line “DP_CONN_DEAD» then appears in the trace file dev_disp. This usually occurs when a user switches off their PC without carrying out the shutdown procedure. A value of «rdisp/keepalive = 0» means that no check occurs.
If the parameter «rdisp/gui_auto_logout» is set, the timeout also applies to HTTP sessions as well as GUI sessions.
Networking tests
There are several situations that can cause a partner not to respond; if none of the above paragraphs can explain your issue, possibly one of the following will fit for your case:
- Workstation issue: a «hardware» issue (e.g. network card broken, but also an old NI driver, an outdated operating system, etc.), a local firewall or antivirus prevents the communication to flow, a OS restriction to the program (the SAPgui in our case) prevents the program to use the network (e.g. User Account Control in the Windows Vista or Server 2008), the program is not running, etc.
- Networking issue: a firewall placed between both parties prevents the communication, a hardware issue (e.g. a damaged cable, node, EM interferences, etc.)
- Server issue (similar to the workstation issue)
Then, the key here will be to determine which is the root cause of this issue. Of course, we will support you closely in case that the a bug in the SAP software is the cause; but please understand that we need to work very closely to you as we do not know your network configuration. It is convenient that you involve here your local networking team.
To further analyze the cause for the frontend not to respond, schedule a detailed network analysis between your application server and the workstation failing until this issue arises again (if ever) or, at least, for some days (even weeks, depending on the periodicity of this subject). This way we will decide if networking issues can be discarded as the root cause of this matter.
NIPING tool is located in the executables directory on any SAP server. You can fetch the latest version of NIPING from the Service Marketplace or, if it is not possible, you can copy the binary from your server binaries directory.
Operating System settings
The following are some typical errors for Microsoft Windows platforms:
- 10048 (WSAEADDRINUSE, SI_EPORT_INUSE) => Only one usage of each socket address (protocol/network address/port) is normally permitted.
- 10054 (WSAECONNRESET, SI_ECONN_BROKEN) => An existing connection was forcibly closed by the remote host.
- 10055 (WSAENOBUFS) => An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
- 10061 (WSAECONNREFUSED) => No connection could be made because the destination computer actively refused it, e.g. in the remote TCP port there is no server program running.
Sometimes these are due to insufficient settings for your operating system due to your particular requirements. This would be the case e.g. if a Java application needs to create a high amount of threads in a very short period of time, everyone with one or more TCP/IP connections; then you should extend the default values for the registry keys MaxUserPort and TCPTimedWaitDelay, otherwise you will get aforementioned error 10055.
Also, we have found a lot of issues with some new features as the Scalable Networking Pack aka. SNP (TCP Chimney Offload feature, RSS, and NetDMA). In particular, we always recommend to disable the «TCP Chimney Offload» feature option on your NIC. In order to do so, you can run from a command prompt “netsh int ip set chimney DISABLED”; run “netsh int ip show chimney” in order to know its current status. Then, reboot the system (it is mandatory!).
Even the “Media Sensing” feature can cause some troubles. Note that this feature is disabled by default in a Windows Server 2003-based server cluster, and so the DisableDHCPMediaSense registry entry has no effect.
Источник
Recv failed with error 10054
When I run a simple winsock program it returns the following error.
recv failed: 10054
Can some one help me to rectify this error? I also activated another udp sender application to inject udp packets into 127.0.0.1 10. Then I wanted to read the packets at port 10 from the code shown below. Is it something workable. Sorry for my little knowledge about how Winsock work.
Winsock program is as follows.
Best Regards
erhct
I might be able to help because I’m learning the same stuff except with TCP but I can’t read what u wrote.
Thanks kbw for the reply!
May be my understanding is wrong. I dont have a server side. I want to basically listen to port 10 and get the datagrams into a buffer. I have a separate program to inject udp packets to 127.0.0.1 port 10. Is this possible with this code or do I have to try something else.
I re-posted the code with proper indentation (pls see the beginning of this discussion). Please help.
Looking forward to your help.
May be my understanding is wrong. I dont have a server side. I want to basically listen to port 10 and get the datagrams into a buffer. I have a separate program to inject udp packets to 127.0.0.1 port 10.
You have a TCP client. If you want to receive UDP traffic, you’ll need to write a client that uses UDP, not TCP.
It is possible to have multiple UDP clients write to any given server:port combination, and the listener can receive those packet. You have to:
1. create a UDP socket
2. bind to the interface:port (probably INADDR_ANY:10 in your case)
3. use recvfrom to listen to receive packets. The function will tell you what socket address it received the packet from.
UDP is much easier to use than TCP, but you should be aware that UDP is «unreliable». It’ll work perfectly on a subnet, but you’ll need error correction if you’re running on a potentially busy LAN or a WAN.
Thanks kbw!
It worked after the modification you proposed. But the program exits after it received the first datagram. How I can make sure it does not exit till I receive all the packets from that port. The code is shown below,
Источник
Recv failed with error 10054
Часовой пояс: UTC + 3 часа
Правила форума
ВНИМАНИЕ! Прежде чем задавать вопрос, ознакомьтесь со ссылками ниже:
Вопросы по отличиям версий SAP, Add-On, EHP — сюда
Вопросы по SAP Front End (SAPlogon, SAPgui, guiXT и т.д.) — сюда
Вопросы по LSMW — сюда
Вопросы по архивации в SAP — сюда
Вопросы по SAP GRC — сюда
Вопросы по SAP Business Workplace (почте SAP) и SAP Office — сюда
Вопросы по miniSAP (SAP mini basis) — сюда
Вопросы по SAP HANA — сюда
Вопросы по лицензированию продуктов SAP — сюда
Operating system call recv failed (error no. 10054)
Страница 1 из 1 | [ Сообщений: 2 ] |
Для печати | Пред. тема | След. тема -> |
Автор | Сообщение | ||
---|---|---|---|
alexivara | |||
Зарегистрирован: |
Кто-нибудь сталкивался с такой руганью в логах? При этом все продолжает работать. 100% появляются такие ошибки когда останавливаю инстанцию. И периодически когда работают в системе. Вот пример лога: Wed Nov 26 11:01:06 2008 Wed Nov 26 11:01:21 2008 Wed Nov 26 11:01:22 2008 И пример лога с другого сервера(идентичное железо) во время работы: Сеть проверял, ни одного пакета не теряется. |
||
Вернуться к началу | |||
alexivara | |||
Зарегистрирован: |
такс, про первый пример суппорт уже ответил: The work processes have a TCP connection to the local gateway. This Anyway when the messages appear during the stopping of the system they Thanks and kind regards,» |
||
Вернуться к началу | |||
Страница 1 из 1 | [ Сообщений: 2 ] |
Часовой пояс: UTC + 3 часа
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения
SAP форум.RU © 2000-. Михаил Вершков
Логотип © 2006 Андрей Горшков
Источник
How to analyze network disconnections shown in system log (BC transaction SM21) ?
System log (transaction SM21) shows network disconnections, e.g.
- Q04 Connection to user 2642 (EXTRACAO), terminal 38 (iguacucp125) lost
- Delete session 001 after error 061
- Operating system call recv failed (error no. 10054)
First at all, consider that a «network disconnection» in the system log (transaction SM21) or in a developer trace is not always meaningful; a typical case is an operating system 10061 error while trying to connect e.g. to the gateway of an SAP system that crashed; obviously, while trying to contact the sapgwXX service of the remote host, the connection cannot be established as the gateway is not running there. In case that still it makes sense to analyze the disconnection, there are several possibilities to analyze the errors:
SAP software: SAPgui and kernel
- Make sure that you are using the latest SAPGUI available.
- Make sure that your current SAP kernel is up-to-date (at least not older than half a year) in your SAP application servers.
- This is the starting point to eliminate that error. There are other possible causes that are to be checked if the issue persists after updating to the latest kernel and GUI patches, namely:
- A user with authorization for transaction SM04 can delete a session of any user; this will generate that message in the syslog and tracefiles.
- If a user is already logged in the system and he logs again with the same user, then he will get a pop up window with three options
- Continue with this logon and end any other logon (then his previous session in the system will be ended, and the information message «Delete session XXX after error 061» will be issued)
- Continue this log on without ending other logo
- Terminate this logon
- Another possibility are problems with the SAPGUI. In this case you should see some error messages after activating the frontend-trace.
Operating System support level: workstations and server(s)
Ensure that your systems are patched to the highest support pack, as well as the network card drivers, etc.
Check your hostname configuration (‘hosts’ files in the workstations, etc.).
Parametrization of SAP system
Sometimes disconnections are not a failure, but a feature offered by the SAP software to avoid the waste of resources due to disconnections caused by users closing the SAPgui without the proper log off, etc. The lines below explain how this mechanism works.
The kernel regularly checks whether a session is still in use and any session that is no longer in use is removed; the check is very simple: if the frontend has not sent any data to the application server for «rdisp/keepalive» seconds, the application server sends a short «ping» message to the frontend. The frontend should answer within the next 40 seconds with «pong», otherwise the application server assumes that the link is dead and releases all resources to the corresponding user. An error line “DP_CONN_DEAD» then appears in the trace file dev_disp. This usually occurs when a user switches off their PC without carrying out the shutdown procedure. A value of «rdisp/keepalive = 0» means that no check occurs.
If the parameter «rdisp/gui_auto_logout» is set, the timeout also applies to HTTP sessions as well as GUI sessions.
Networking tests
There are several situations that can cause a partner not to respond; if none of the above paragraphs can explain your issue, possibly one of the following will fit for your case:
- Workstation issue: a «hardware» issue (e.g. network card broken, but also an old NI driver, an outdated operating system, etc.), a local firewall or antivirus prevents the communication to flow, a OS restriction to the program (the SAPgui in our case) prevents the program to use the network (e.g. User Account Control in the Windows Vista or Server 2008), the program is not running, etc.
- Networking issue: a firewall placed between both parties prevents the communication, a hardware issue (e.g. a damaged cable, node, EM interferences, etc.)
- Server issue (similar to the workstation issue)
Then, the key here will be to determine which is the root cause of this issue. Of course, we will support you closely in case that the a bug in the SAP software is the cause; but please understand that we need to work very closely to you as we do not know your network configuration. It is convenient that you involve here your local networking team.
To further analyze the cause for the frontend not to respond, schedule a detailed network analysis between your application server and the workstation failing until this issue arises again (if ever) or, at least, for some days (even weeks, depending on the periodicity of this subject). This way we will decide if networking issues can be discarded as the root cause of this matter.
NIPING tool is located in the executables directory on any SAP server. You can fetch the latest version of NIPING from the Service Marketplace or, if it is not possible, you can copy the binary from your server binaries directory.
Operating System settings
The following are some typical errors for Microsoft Windows platforms:
- 10048 (WSAEADDRINUSE, SI_EPORT_INUSE) => Only one usage of each socket address (protocol/network address/port) is normally permitted.
- 10054 (WSAECONNRESET, SI_ECONN_BROKEN) => An existing connection was forcibly closed by the remote host.
- 10055 (WSAENOBUFS) => An operation on a socket could not be performed because the system lacked sufficient buffer space or because a queue was full.
- 10061 (WSAECONNREFUSED) => No connection could be made because the destination computer actively refused it, e.g. in the remote TCP port there is no server program running.
Sometimes these are due to insufficient settings for your operating system due to your particular requirements. This would be the case e.g. if a Java application needs to create a high amount of threads in a very short period of time, everyone with one or more TCP/IP connections; then you should extend the default values for the registry keys MaxUserPort and TCPTimedWaitDelay, otherwise you will get aforementioned error 10055.
Also, we have found a lot of issues with some new features as the Scalable Networking Pack aka. SNP (TCP Chimney Offload feature, RSS, and NetDMA). In particular, we always recommend to disable the «TCP Chimney Offload» feature option on your NIC. In order to do so, you can run from a command prompt “netsh int ip set chimney DISABLED”; run “netsh int ip show chimney” in order to know its current status. Then, reboot the system (it is mandatory!).
Even the “Media Sensing” feature can cause some troubles. Note that this feature is disabled by default in a Windows Server 2003-based server cluster, and so the DisableDHCPMediaSense registry entry has no effect.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
DWORD WINAPI __conClients1(LPVOID par) {//Igra 1 int index = (int)par; //don't use char _msg[256]; char _NAME1[16]; char _NAME2[16]; char Welcome[] = "[SERVER] Connection succesfful!"; char SendPlayers[] = "[SERVER] if you ready write !ready."; char EntName[] = "Enter your name!"; system("echo HERE1"); cout << _newCon[0] << endl; cout << _newCon[1] << endl; if (send(_newCon[0], Welcome, sizeof(Welcome), 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "FirstSend1"); } if (send(_newCon[1], Welcome, sizeof(Welcome), 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "SecndSend1"); } if (send(_newCon[0], SendPlayers, sizeof(SendPlayers), 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "FirstSend2"); } if (send(_newCon[1], SendPlayers, sizeof(SendPlayers), 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "SecndSend2"); } if (recv(_newCon[0], _msg, 256, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "FirstRecv1"); } if (_msg[0] == '!' && _msg[1] == 'r' && _msg[2] == 'e' && _msg[3] == 'a' && _msg[4] == 'd' && _msg[5] == 'y') { if (send(_newCon[0], "You are ready!", 15, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "FirstSend4"); } } cout << _msg << endl; if(recv(_newCon[1], _msg, 256, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "SecRecv1"); } if (_msg[0] == '!' && _msg[1] == 'r' && _msg[2] == 'e' && _msg[3] == 'a' && _msg[4] == 'd' && _msg[5] == 'y') { if(send(_newCon[1], "You are ready!", 15, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "SecSend4"); } } cout << _msg << endl; if(send(_newCon[0], EntName, sizeof(EntName), 0) == SOCKET_ERROR){ __Error(WSAGetLastError(), "FirstSend3"); } if(send(_newCon[1], (char*)EntName, sizeof(EntName), 0) == SOCKET_ERROR){ __Error(WSAGetLastError(), "SecndSend3"); } if(recv(_newCon[0], _NAME1, 16, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "FirstRecv2"); } else { cout << "Player1: <" << _NAME1 << "> Have IP adress: " << inet_ntoa(saIn.sin_addr) << endl; } if(recv(_newCon[1], _NAME2, 16, 0) == SOCKET_ERROR) { __Error(WSAGetLastError(), "SecRecv1"); } else { cout << "Player2: <" << _NAME2 << "> Have IP adress: " << inet_ntoa(saIn.sin_addr) << endl; } return 0; } VOID __SockC() { loHost = gethostbyname(""); loIp = inet_ntoa(*(struct in_addr*)*loHost->h_addr_list); saIn.sin_family = AF_INET; saIn.sin_addr.s_addr = inet_addr(loIp); saIn.sin_port = htons(2014); cout << inet_ntoa(saIn.sin_addr) << "Server IPn"; cout << "Use this ip for connect to servern"; SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (_sock == 0) { __Error(WSAGetLastError(), "SocketCreate"); } bind(_sock, (SOCKADDR*)&saIn, sizeof(saIn)); listen(_sock, _max_connections); //first2 __FIR; //second2 __SEC; int addr = sizeof(saIn); for (int i = 0; i < 2; i++) { _sockIn = accept(_sock, (SOCKADDR*)&saIn, &addr); if (_sockIn == 0) { __Error(WSAGetLastError(), "accept"); } else { cout << inet_ntoa(saIn.sin_addr) << "Conecctedn"; send(_sockIn, "Successful", 11, 0); } if (i == 0) { _newCon[i] = _sockIn; cout << _newCon[i] << endl; } if (i == 1) { _newCon[i] = _sockIn; cout << _newCon[i] << endl; } /* if (i == 2) __SEC._sk2 = _sockIn; if (i == 3) __SEC._sk2 = _sockIn;*/ if (_count == 1) {//count % 2 == 1 if (CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)__conClients1, (LPVOID)(i), NULL, NULL) == 0) __Error(WSAGetLastError(), "CreateThread"); } /* if (_count == 3) { if (CreateThread(NULL, NULL, (LPTHREAD_START_ROUTINE)__conClients2, (LPVOID)&__SEC, NULL, NULL) == 0) __Error(WSAGetLastError(), "CreateThread"); }*/ _count++; } cout << "[SERVER]{Create successfull}n"; //Описание создания сервера }; |
Hi All,
I am facing the above problem after the updation of kernel , igs and JVM in PI 7.1
The java is not coming up.
The disp+work is having the error
(10054: WSAECONNRESET: Connection reset by peer)
J2EE server info
start = TRUE
state = STARTED
pid = 4792
argv[0] = F:usrsapPS3DVEBMGS00exejstart.EXE
argv[1] = F:usrsapPS3DVEBMGS00exejstart.EXE
argv[2] = pf=F:usrsapPS3SYSprofilePS3_DVEBMGS00_hydhtc165182d
argv[3] = -DSAPSTART=1
argv[4] = -DCONNECT_PORT=64952
argv[5] = -DSAPSYSTEM=00
argv[6] = -DSAPSYSTEMNAME=PS3
argv[7] = -DSAPMYNAME=hydhtc165182d_PS3_00
argv[8] = -DSAPPROFILE=F:usrsapPS3SYSprofilePS3_DVEBMGS00_hydhtc165182d
argv[9] = -DFRFC_FALLBACK=ON
argv[10] = -DFRFC_FALLBACK_HOST=localhost
start_lazy = 0
start_control = SAP J2EE startup framework
DpJ2eeStart: j2ee state = STARTED
DpJ2eeLogin: j2ee state = CONNECTED
Fri Apr 03 13:05:33 2009
***LOG Q0I=> NiIRead: P=127.0.0.1:4802; L=0.0.0.0:64952: recv (10054: WSAECONNRESET: Connection reset by peer) [nixxi.cpp 4857]
-
ERROR => NiIRead: SiRecv failed for hdl 33/sock 1216
(SI_ECONN_BROKEN/10054; I4; ST; P=127.0.0.1:4802; L=0.0.0.0:64952) [nixxi.cpp 4857]
DpJ2eeMsgProcess: j2ee state = CONNECTED (NIECONN_BROKEN)
DpIJ2eeShutdown: send SIGINT to SAP J2EE startup framework (pid=4792)
-
ERROR => DpProcKill: kill failed [dpntdisp.c 396]
DpIJ2eeShutdown: j2ee state = SHUTDOWN
I have already checked note 155147 and 413330 but i dont think so i am facing network issues
The server was working fine until the applying of the kernels but once i applied the kernel pathches the java dint come up.
Any pointers would help
Rgds
Aditya
// Server.cpp : Defines the entry point for the console application.
//
#include «stdafx.h»
//******************* SERVER PROG ****************
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib, «Ws2_32.lib»)
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT 27015
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
#pragma comment (lib, «Ws2_32.lib»)
#pragma comment (lib, «Mswsock.lib»)
#pragma comment (lib, «AdvApi32.lib»)
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT «27015»
int __cdecl main(void)
{
WSADATA wsaData;
SOCKET ListenSocket = INVALID_SOCKET,
ClientSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
hints;
char recvbuf[DEFAULT_BUFLEN];
int iResult, iSendResult;
int recvbuflen = DEFAULT_BUFLEN;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf(«WSAStartup failed with error: %dn», iResult);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if ( iResult != 0 ) {
printf(«getaddrinfo failed with error: %dn», iResult);
WSACleanup();
return 1;
}
// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf(«socket failed with error: %ldn», WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind( ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf(«bind failed with error: %dn», WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf(«listen failed with error: %dn», WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
printf(«start accept:n»);
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf(«accept failed with error: %dn», WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();
return 1;
}
printf(«end accept:n»);
// No longer need server socket
closesocket(ListenSocket);
printf(«end accept:n»);
printf(«start Receive:n»);
// Receive until the peer shuts down the connection
do {
iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
printf(«Bytes received: %dn», iResult);
// Echo the buffer back to the sender
iSendResult = send( ClientSocket, recvbuf, iResult, 0 );
if (iSendResult == SOCKET_ERROR) {
printf(«send failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf(«Bytes sent: %dn», iSendResult);
}
else if (iResult == 0)
printf(«Connection closing…n»);
else {
printf(«recv failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
} while (iResult > 0);
// shutdown the connection since we’re done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf(«shutdown failed with error: %dn», WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
-
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
Привет всем!
У меня проблема. Написал программу (точнее 3 программы — одна координирующая, одна — принимающая пакеты, другая — отправляющая пакеты), которая передает звук, захваченный с микрофона, по сети этой же программе на другой машине. В общем, программа-телефон для локальной сети.
Моя программа состоит из 3-х частей:
1) LANPhone (координирующая, интерфейс пользователю и все такое)
2) SendWave (ловит звук с микрофона и отправляет по сети звуковые буферы программе RecvWave на другой машине)
3) RecvWave (принимает звуковые буферы, посланные программой SendWave на удаленной машине, и воспроизводит звук)LANPhone может работать как в режиме клиента (когда мы «звоним» кому-то), так и в режиме сервера (когда до нас «дозванивается» кто-то).
У меня стоит Kerio WinRoute Firewall, правила настроены верно. Так вот, когда фаер включен, SendWave на сервере почему-то сначала работает (посылает пакеты секунд 5-10), а потом завершается. Я выяснил, что это из-за того, что функция recv в SendWave завершается с ошибкой 10054 (Удаленный хост принудительно разорвал существующее подключение).
Если пробовать с выключенным WinRoute, то все ОК.
Нашел в Сети почти аналогичную программу lanic, она работает без проблем и с включенным WinRoute. Не пойму, почему фаер внезапно обрубает соединение.
В настройках вроде никаких особых ограничений нет. -
mathio
New Member
- Публикаций:
-
0
- Регистрация:
- 16 июн 2007
- Сообщения:
- 110
В этой ситуации можно что-то посоветовать лишь видя картину в деталях.
Тоесть нужны либо исходники приемо-передатчиков, либо, что проще, закапчурите весь сетевой обмен(весь трафик) каким-нибудь Ethereal’ом(желательно, т.к. имею оное и смогу помочь) и приаттачьте логи сюда/либо в ЛС киньте на них линк. -
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
Вот исходник SendWave. Исходник еще сырой и неоптимизированный, поэтому просьба не ругаться.
Заметим, что флаг fStopSendWave устанавливается в TRUE, когда recv возвращается с ошибкой. Если fStopSendWave == TRUE, то происходит процесс завершения программы.
-
BOOL fStopSendWave = FALSE;
-
DWORD dwMainThreadId = 0;
-
HANDLE hSendWaveThread = INVALID_HANDLE_VALUE;
-
BOOL fStartWasSended = FALSE;
-
#define WM_USER_START WM_USER + 1024
-
#define WM_USER_STOP WM_USER + 1025
-
DWORD g_dwAllocatedBuffers;
-
DWORD g_dwSendWaveThreadId;
-
g_dwAllocatedBuffers = 0;
-
UINT BytesPerSample = (BitsPerSample + 7) / 8;
-
Format.wFormatTag = WAVE_FORMAT_PCM;
-
Format.nChannels = Channels;
-
Format.wBitsPerSample = BitsPerSample;
-
Format.nBlockAlign = (WORD)(Channels * BytesPerSample);
-
Format.nSamplesPerSec = SampleRate;
-
Format.nAvgBytesPerSec = Format.nSamplesPerSec * Format.nBlockAlign;
-
Res = waveInOpen(&g_hWaveIn, 0, &Format, g_dwSendWaveThreadId, 0, CALLBACK_THREAD);
-
if (Res != MMSYSERR_NOERROR) {
-
UINT BufferSize = (Format.nSamplesPerSec * BufferMS / Buffers + 500) / 1000;
-
BufferSize *= Format.nBlockAlign;
-
for (int N = Buffers; N > 0; N—) {
-
char *Buf = (char *)GlobalAlloc(GMEM_FIXED, BufferSize);
-
WAVEHDR *Hdr = (WAVEHDR *)LocalAlloc(LMEM_FIXED, sizeof(*Hdr));
-
Hdr->dwBufferLength = BufferSize;
-
waveInPrepareHeader (g_hWaveIn, Hdr, sizeof (*Hdr));
-
Res = waveInAddBuffer (g_hWaveIn, Hdr, sizeof (*Hdr));
-
if (Buf && Hdr && Res == MMSYSERR_NOERROR) {
-
GlobalFree ((HGLOBAL)Buf);
-
SendMessage(hMainWnd, WM_CLOSE, 0, 0);
-
VOID ReleaseBuffer(WAVEHDR *Hdr) {
-
GlobalFree((HGLOBAL)Hdr->lpData);
-
if (!g_dwAllocatedBuffers) {
-
PostThreadMessage(g_dwSendWaveThreadId, WM_QUIT, 0, 0);
-
DWORD WINAPI SendWaveThreadProc(LPVOID lpParam) {
-
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
-
while (GetMessage(&msg, NULL, 0, 0) == TRUE) {
-
WAVEHDR *Hdr = (WAVEHDR *)msg.lParam;
-
waveInUnprepareHeader(g_hWaveIn, Hdr, sizeof(*Hdr));
-
if (send(g_Socket, (const char *)Hdr, sizeof(*Hdr), 0) == SOCKET_ERROR) {
-
bytesRecv = recv(g_Socket, recvbuf, sizeof(recvbuf), 0);
-
// Ошибка бывает здесь: WSAGetLastError() == 10054
-
waveInPrepareHeader(g_hWaveIn, Hdr, sizeof (*Hdr));
-
waveInAddBuffer(g_hWaveIn, Hdr, sizeof (*Hdr));
-
if (send(g_Socket, (const char *)Hdr->lpData, Hdr->dwBufferLength, 0) == SOCKET_ERROR) {
-
bytesRecv = recv(g_Socket, recvbuf, sizeof(recvbuf), 0);
-
// Ошибка бывает здесь: WSAGetLastError() == 10054
-
waveInPrepareHeader(g_hWaveIn, Hdr, sizeof(*Hdr));
-
waveInAddBuffer(g_hWaveIn, Hdr, sizeof(*Hdr));
-
waveInPrepareHeader(g_hWaveIn, Hdr, sizeof(*Hdr));
-
waveInAddBuffer(g_hWaveIn, Hdr, sizeof(*Hdr));
-
DWORD WINAPI Start(LPVOID lpParam) {
-
g_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
-
sockaddr_in clientService;
-
clientService.sin_family = AF_INET;
-
clientService.sin_addr.s_addr = dwIPAddr;
-
clientService.sin_port = htons(wPort);
-
while (connect(g_Socket, (SOCKADDR*)&clientService, sizeof(clientService)) == SOCKET_ERROR && !fStopSendWave) {
-
SendMessage(hMainWnd, WM_CLOSE, 0, 0);
-
SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
-
hSendWaveThread = CreateThread(NULL, 0, SendWaveThreadProc, NULL, CREATE_SUSPENDED, &g_dwSendWaveThreadId);
-
ResumeThread(hSendWaveThread);
-
if (waveInStart(g_hWaveIn) == MMSYSERR_NOERROR) {
-
CloseHandle(hSendWaveThread);
-
hSendWaveThread = INVALID_HANDLE_VALUE;
-
TerminateThread(hSendWaveThread, 0);
-
CloseHandle(hSendWaveThread);
-
hSendWaveThread = INVALID_HANDLE_VALUE;
-
SendMessage(hMainWnd, WM_CLOSE, 0, 0);
-
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
-
CloseHandle(CreateThread(NULL, 0, Start, NULL, 0, NULL));
-
return DefWindowProc(hwnd, uMsg, wParam, lParam);
-
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR lpCmdLine, int nCmdShow) {
-
// Ограничиваем память процесса на всякий случай
-
HANDLE hJob = CreateJobObject(NULL, NULL);
-
AssignProcessToJobObject(hJob, GetCurrentProcess());
-
JOBOBJECT_EXTENDED_LIMIT_INFORMATION lim;
-
lim.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_PROCESS_MEMORY;
-
lim.ProcessMemoryLimit = 1024 * 1024 * 10;
-
SetInformationJobObject(hJob, JobObjectExtendedLimitInformation, &lim, sizeof(lim));
-
int nWSARes = WSAStartup(MAKEWORD(2, 2), &wsaData);
-
if (nWSARes != NO_ERROR) {
-
lpWndClass.cbClsExtra = 0;
-
lpWndClass.cbWndExtra = 0;
-
lpWndClass.hbrBackground = 0;
-
lpWndClass.hInstance = hInstance;
-
lpWndClass.lpfnWndProc = WindowProc;
-
lpWndClass.lpszClassName = _TEXT(«SendWave»);
-
lpWndClass.lpszMenuName = 0;
-
RegisterClass(&lpWndClass);
-
hMainWnd = CreateWindowEx(0, lpWndClass.lpszClassName, lpWndClass.lpszClassName, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL);
-
while ((bRet = GetMessage(&msg, hMainWnd, 0, 0)) != 0) {
-
mathio
New Member
- Публикаций:
-
0
- Регистрация:
- 16 июн 2007
- Сообщения:
- 110
Если честно, то по сетевому дампу быстрее и проще локализовать проблему.
-
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
ОК, тогда что мне использовать?
-
mathio
New Member
- Публикаций:
-
0
- Регистрация:
- 16 июн 2007
- Сообщения:
- 110
http://www.ethereal.com/download.html
Нужно сделать полный лог, включающий моменты установления соединения между клиентом-сервером и до его «внезапного» обрыва. Плюс к этому желательно укажите IP адреса клиента и сервера, чтоб не тратить время. -
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
192.168.1.1 — клиент (кто «дозванивался»)
192.168.1.2 — сервер (куда «дозванивались»)Порт 22221 используется программой LANPhone
Порт 22222 используется RecvWave и SendWaveПри логе я поставил фильтр, чтобы отслеживались только эти IP адреса.
-
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
лог: http://webfile.ru/download.php?id=1494588
-
mathio
New Member
- Публикаций:
-
0
- Регистрация:
- 16 июн 2007
- Сообщения:
- 110
Хм, в конце лога все нормально, т.е. даже такое впечатление, что соединение не порвалось. По крайней мере нет ни FIN’ов, ни TCP ретрансмитта с какой-либо стороны в следствии неких тайм-аутов.
Лог действительно создавался вплоть _до_ разрыва связи?(т.е. включая и разрыв)А вообще, у меня было предположение, что на каком-то этапе общения происходит рассинхронизация и одна из сторон «долбится» в уже закрытый порт.
-
Crash
New Member
- Публикаций:
-
0
- Регистрация:
- 23 авг 2004
- Сообщения:
- 73
Да, лог закрывался уже после того, как были закрыты обе программы.
Рассинхронизация в принципе не может быть. Клиент посылает данные, а сервер отвечает. После того, как сервер ответил, клиент снова посылает и т.д.Тут почему-то файервол мешает. Без него все нормально.
- Forum
- General C++ Programming
- WinSock program error
WinSock program error
Pages: 12
Hi All,
When I run a simple winsock program it returns the following error.
recv failed: 10054
Can some one help me to rectify this error? I also activated another udp sender application to inject udp packets into 127.0.0.1 10. Then I wanted to read the packets at port 10 from the code shown below. Is it something workable. Sorry for my little knowledge about how Winsock work.
Winsock program is as follows.
|
|
Best Regards
erhct
Last edited on
Hey, can u edit ur code with code that has proper indentation like this:
|
|
I might be able to help because I’m learning the same stuff except with TCP but I can’t read what u wrote…
Last edited on
The server has closed the connection. You need to take a look at the server, the client code looks fine.
Thanks kbw for the reply!
May be my understanding is wrong. I dont have a server side. I want to basically listen to port 10 and get the datagrams into a buffer. I have a separate program to inject udp packets to 127.0.0.1 port 10. Is this possible with this code or do I have to try something else.
Hi Soranz,
I re-posted the code with proper indentation (pls see the beginning of this discussion). Please help.
Looking forward to your help.
Regards
erhct
May be my understanding is wrong. I dont have a server side. I want to basically listen to port 10 and get the datagrams into a buffer. I have a separate program to inject udp packets to 127.0.0.1 port 10.
You have a TCP client. If you want to receive UDP traffic, you’ll need to write a client that uses UDP, not TCP.
It is possible to have multiple UDP clients write to any given server:port combination, and the listener can receive those packet. You have to:
1. create a UDP socket
2. bind to the interface:port (probably INADDR_ANY:10 in your case)
3. use recvfrom to listen to receive packets. The function will tell you what socket address it received the packet from.
UDP is much easier to use than TCP, but you should be aware that UDP is «unreliable». It’ll work perfectly on a subnet, but you’ll need error correction if you’re running on a potentially busy LAN or a WAN.
Last edited on
Thanks kbw!
It worked after the modification you proposed. But the program exits after it received the first datagram. How I can make sure it does not exit till I receive all the packets from that port. The code is shown below,
|
|
Looking forward to your comments…
Regards
erhct
Should there be a loop around iResult = recvfrom(RecvSocket, ...
?
Thanks Soranz! I managed to collect all datagram packets send by the sender programme through a loop. But still the programe listen to incoming packets.
How I can stop listening when there are no more packets for instance after 5s.
Regards
erhct
How I can stop listening when there are no more packets for instance after 5s.
You can use select() to wait for incoming packets with a timeout.
If the socket is available for read, you read it. If select() timed out, you drop out of the loop.
Thanks Kbw!!!
Still I couldn’t figure out how select() works with a listening socket. Can someone provide a sample code how select() works with udp listening socket.
Regards
erhct
select() allows you wait for sets of sockets to signal for read, write or error. An you can set a timeout.
There are macros that manage the sets and allow to test if one is set. If your case you’ll only be testing one socket for read, with a 5 sec timeout.
1. You define an fd_set and initialise it with FD_ZERO.
2. You use FD_SET to add your socket to the set.
3. Initialise a struct timeval record with { 5, 0 } for 5 sec, 0 nsec
4. Call select() with the read set specified and zero for the write and error. It returns the number of sockets signalled, zero for timeout.
5. If select() returned 1, you can read the socket. As you only have the one socket, you can be sure that FD_ISSET will confirm that your socket is readable.
Thanks Soranz and Kbw! I managed to implement the timeout using the select() function after specifying necessary parameters.
Can you pls shed some light on whether I can find the index no of received udp packets. In this case I can find the missing packets from the total transmitted packets.
Looking forward to hear from you
Best Regards
erhct
There is no index number of a udp packet. You have to maintain that yourself.
Thanks!
I created a separate thread to read udp packets. But when I tried to call a function declared with the main programme (main()) it does not identify the function.
Error: undeclared identifier
My function declared as follows:
DWORD CALLBACK xxx()
I called this function within the thread from another function using the following syntax
function(&xxx,etc);
thread is created as follows.
|
|
This function works well within the main() but not within the thread()
I think I am not calling the function correctly.
Can someone help pls.
Regards
erhct
I don’t understand the problem from your description. Can you post some code that demonstrates what the problem is and what you’ve done.
|
|
When I call streamcreate function from the thread (read_udp_data) it returns an error during building (undeclared identifier)
Is all the code in the same file as you imply above?
What is the exact error produced by the compiler?
Hi kbw,
Indeed the streamcreate() is from a separate dll. But it is linked to the main progrm.
The error error C2065: ‘MyStreamWriter’ : undeclared identifier
When I call this function within the main() (e.g. streamcreate(&MyStreamWriter);)it works fine But not from the thread…
Probably I am not passing an instance of MystreamWriter correctly to the streamcreate()
Pages: 12