I am having some trouble implementing TCP IOCP client. I have implemented kqueue on Mac OSX so was looking to do something similar on windows and my understanding is that IOCP is the closest thing. The main problem is that GetCompetetionStatus is never returning and always timeouts out. I assume I am missing something when creating the handle to monitor, but not sure what. This is where I have gotten so far:
My connect routine: (remove some error handling for clarity )
struct sockaddr_in server;
struct hostent *hp;
SOCKET sckfd;
WSADATA wsaData;
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if ((hp = gethostbyname(host)) == NULL)
return NULL;
WSASocket(AF_INET,SOCK_STREAM,0,NULL,0,WSA_FLAG_OVERLAPPED)
if ((sckfd = WSASocket(AF_INET,SOCK_STREAM,0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
{
printf("Error at socket(): Socket\n");
WSACleanup();
return NULL;
}
server.sin_family = AF_INET;
server.sin_port = htons(port);
server.sin_addr = *((struct in_addr *)hp->h_addr);
memset(&(server.sin_zero), 0, 8);
//non zero means non blocking. 0 is blocking.
u_long iMode = -1;
iResult = ioctlsocket(sckfd, FIONBIO, &iMode);
if (iResult != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", iResult);
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)sckfd, hNewIOCP , ulKey, 0);
connect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr));
//WSAConnect(sckfd, (struct sockaddr *)&server, sizeof(struct sockaddr),NULL,NULL,NULL,NULL);
return sckfd;
Here is the send routine: ( also remove some error handling for clarity )
IOPortConnect(int ServerSocket,int timeout,string& data){
char buf[BUFSIZE];
strcpy(buf,data.c_str());
WSABUF buffer = { BUFSIZE,buf };
DWORD bytes_recvd;
int r;
ULONG_PTR ulKey = 0;
OVERLAPPED overlapped;
OVERLAPPED* pov = NULL;
HANDLE port;
HANDLE hNewIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, ulKey, 0);
CreateIoCompletionPort((HANDLE)ServerSocket, hNewIOCP , ulKey, 0);
BOOL get = GetQueuedCompletionStatus(hNewIOCP,&bytes_recvd,&ulKey,&pov,timeout*1000);
if(!get)
printf("waiton server failed. Error: %d\n",WSAGetLastError());
if(!pov)
printf("waiton server failed. Error: %d\n",WSAGetLastError());
port = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (u_long)0, 0);
SecureZeroMemory((PVOID) & overlapped, sizeof (WSAOVERLAPPED));
r = WSASend(ServerSocket, &buffer, 1, &bytes_recvd, NULL, &overlapped, NULL);
printf("WSA returned: %d WSALastError: %d\n",r,WSAGetLastError());
if(r != 0)
{
printf("WSASend failed %d\n",GetLastError());
printf("Bytes transfered: %d\n",bytes_recvd);
}
if (WSAGetLastError() == WSA_IO_PENDING)
printf("we are async.\n");
CreateIoCompletionPort(port, &overlapped.hEvent,ulKey, 0);
BOOL test = GetQueuedCompletionStatus(port,&bytes_recvd,&ulKey,&pov,timeout*1000);
CloseHandle(port);
return true;
}
Any insight would be appreciated.
You are associating the same socket with multiple IOCompletionPorts. I'm sure thats not valid. In your IOPortConnect function (Where you do the write) you call CreateIOCompletionPort 4 times passing in one shot handles.
My advice:
Create a single IOCompletion Port (that, ultimately, you associate numerous sockets with).
Create a pool of worker threads (by calling CreateThread) that each then block on the IOCompletionPort handle by calling GetQueuedCompletionStatus in a loop.
Create one or more WSA_OVERLAPPED sockets, and associate each one with the IOCompletionPort.
Use the WSA socket functions that take an OVERLAPPED* to trigger overlapped operations.
Process the completion of the issued requests as the worker threads return from GetQueuedCompletionStatus with the OVERLAPPED* you passed in to start the operation.
Note: WSASend returns both 0, and SOCKET_ERROR with WSAGetLastError() as WSA_IO_PENDING as codes to indicate that you will get an IO Completion Packet arriving at GetQueuedCompletionStatus. Any other error code means you should process the error immediately as an IO operation was not queued so there will be no further callbacks.
Note2: The OVERLAPPED* passed to the WSASend (or whatever) function is the OVERLAPPED* returned from GetQueuedCompletionStatus. You can use this fact to pass more context information with the call:
struct MYOVERLAPPED {
OVERLAPPED ovl;
};
MYOVERLAPPED ctx;
WSASend(...,&ctx.ovl);
...
OVERLAPPED* pov;
if(GetQueuedCompletionStatus(...,&pov,...)){
MYOVERLAPPED* pCtx = (MYOVERLAPPED*)pov;
Chris has dealt with most of the issues and you've probably already looked at plenty of example code, but...
I've got some free IOCP code that's available here: http://www.serverframework.com/products---the-free-framework.html
There are also several of my CodeProject articles on the subject linked from that page.
Related
Please understand that I am new to IOCP and my code may not be so perfect.
I tried many examples from around here, neither one helps me.
My actual problem is in the client side, I have no idea if I am connecting properly to a IOCP server, neither if I send the data properly and recv gives me WSAerror 10038 ...
WSADATA wsd;
struct addrinfo *result = NULL, *ptr = NULL, hints;
WSAOVERLAPPED RecvOverlapped;
SOCKET ConnSocket = INVALID_SOCKET;
WSABUF DataBuf;
DWORD RecvBytes, Flags;
CRITICAL_SECTION criti;
char buffer[DATA_BUFSIZE];
int err = 0;
int rc;
// Load Winsock
rc = WSAStartup(MAKEWORD(2, 2), &wsd);
if (rc != 0) {
return 1;
}
// Make sure the hints struct is zeroed out
SecureZeroMemory((PVOID)& hints, sizeof(struct addrinfo));
// Initialize the hints to retrieve the server address for IPv4
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
rc = getaddrinfo(IP, Port, &hints, &result);
if (rc != 0) {
return 1;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
if ((ConnSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET){
freeaddrinfo(result);
return 1;
}
rc = connect(ConnSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (rc == SOCKET_ERROR) {
if (WSAECONNREFUSED == (err = WSAGetLastError())) {
closesocket(ConnSocket);
ConnSocket = INVALID_SOCKET;
continue;
}
freeaddrinfo(result);
closesocket(ConnSocket);
WSACleanup();
return 1;
}
break;
}
if (ConnSocket == INVALID_SOCKET) {
freeaddrinfo(result);
return 1;
}
int nZero = 0;
// Make sure the RecvOverlapped struct is zeroed out
SecureZeroMemory((PVOID)& RecvOverlapped, sizeof(WSAOVERLAPPED));
// Create an event handle and setup an overlapped structure.
RecvOverlapped.hEvent = WSACreateEvent();
if (RecvOverlapped.hEvent == NULL) {
freeaddrinfo(result);
closesocket(ConnSocket);
return 1;
}
DataBuf.len = DATA_BUFSIZE;
DataBuf.buf = buffer;
// send data to server here?
// removed the packets, it`s not supposed to be public
// Call WSARecv until the peer closes the connection
// or until an error occurs
while (1) {
Flags = 0;
RecvBytes = 0;
rc = WSARecv(ConnSocket, &DataBuf, 1, &RecvBytes, &Flags, &RecvOverlapped, NULL);
if ((rc == SOCKET_ERROR) && (WSA_IO_PENDING != (err = WSAGetLastError()))) {
closesocket(ConnSocket);
break;
}
rc = WSAWaitForMultipleEvents(1, &RecvOverlapped.hEvent, TRUE, INFINITE, TRUE);
if (rc == WSA_WAIT_FAILED) {
break;
}
rc = WSAGetOverlappedResult(ConnSocket, &RecvOverlapped, &RecvBytes, FALSE, &Flags);
if (rc == FALSE) {
break;
}
// here I have a protocol where I read the received data
WSAResetEvent(RecvOverlapped.hEvent);
// If 0 bytes are received, the connection was closed
if (RecvBytes == 0)
break;
}
WSACloseEvent(RecvOverlapped.hEvent);
closesocket(ConnSocket);
freeaddrinfo(result);
WSACleanup();
I expect to be able to send data and receive the response from IOCP, but if I send 3 packets, I receive back 2 only or sometimes even 1, when I am sending 3 packets back.
Can some show me a working example to connect and send+recv data to a IOCP server?
Many thanks!
You're using TCP. TCP is a stream protocol, not a datagram protocol. You cannot tell it what packets to send, and it cannot tell you what packets it received (it doesn't even know because that's handled at the IP layer). It just doesn't work that way.
This sentence is packed with wisdom: "TCP is a bidirectional, connection oriented, byte stream protocol that provides reliable, ordered delivery but does not preserve application message boundaries." Punch "TCP" into your favorite search engine and study until you understand precisely what every word in that sentence means. You will never write reliable, or even correct, TCP code until you do.
Whether the server is using IOCP or some other internal architecture has no effect on clients. That's totally invisible.
this is my first time asking a question, and the first time I couldn't find an answer by just searching this site. so please go easy on me if I am doing it wrong.
Using Winsock. I need to send AND receive a packet of information to another computer running the same program. the type of connection should be UDP(non blocking I guess?)and using a data-coupled model.
do I need to be sending and receiving the information using different threads?
I know the data sends just fine but it is not being received at all.
I can easily have on program send and a completely different program recv but it seems the principles don't carry over to what I am trying to do.
should I use the same sockaddr_in struct for the recvfrom and sendto? or can they use the same one? how about slen? doesn't matter I have tried both and neither work.I have tried using one port to send and one to recieve, I have tried having one port to do both. nothing. I am relatively new to Winsock so sorry if I sound hopeless or missing something horribly obvious. At this point I just really need some help or at least a point in the right direction I don't care how many ports I just want to see the recv printf incoming with the right data.
winsock errors are
bind failed 10048 and recv failed 10022
I will also mention I looked into a concept called setsockopt suggested by MSDN but it just ended up furthering my confusion. am I missing something?
here are some relevant functions.
void UDPNetwork::initserver()
{
initRemote();
slen2= sizeof(si_other);
if ((_recvSocket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET)
{
printf("failed to create socket: %d", WSAGetLastError());
}
_recvSocket = (AF_INET, SOCK_DGRAM, 0);
memset((char *)&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
if (bind(_recvSocket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("Bind failed with error code : %d",
WSAGetLastError());
/* system("PAUSE");
exit(EXIT_FAILURE);*/
}
}
void UDPNetwork::initclient(){
slen = sizeof(si_other);
_sendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (_sendSocket == SOCKET_ERROR)
{
printf("failed to create socket... ");
exit(EXIT_FAILURE);
}
memset((char *)&si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;
si_other.sin_port = htons(PORT);
si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);
}
void UDPNetwork::send(float x, float y, float z)
{
sprintf(bufOut,"%f,%f,%f", x, y, z);
if (sendto(_sendSocket, bufOut, strlen(bufOut), 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR)
{
printf("sento() failed with error code : d%", WSAGetLastError());
exit(EXIT_FAILURE);
}
//printf("Sent: %s\n", bufOut);
}
void UDPNetwork::recv(char *msg)
{
float ax = 0; float ay = 0; float az = 0;
memset(msg, '\0', BUFLEN);
recv_len = recvfrom(_recvSocket, msg, BUFLEN, 0, (struct sockaddr*) &si_other, &slen);
int nError = WSAGetLastError();
if (nError != WSAEWOULDBLOCK&&nError != 0);
{
printf("Recv failed with error code : %d",
WSAGetLastError());
//system("PAUSE");
//exit(EXIT_FAILURE);
}
recv = buf;
sscanf_s(msg, "'%f,%f,%f", &ax,&ay,&az);
printf("RECV: %f %f %f\n", ax, ay, az);
}
Most UDP receivers will send data back to the same IP:Port that the reeived data was sent from. So by creating two different sockets, you are using two different IP:Port pairs, which is likely why you are not receiving data. The data is likely being sent to a different IP:Port than the one you are reading on.
For UDP, you usually do not need to create separate send and receive sockets. You can create one UDP socket and use it for both sending and receiving, so the sending IP:Port matches the receiving IP:Port. The only time you should need to create separate sockets is if the receiver intentionally sends its data to a different IP:Port than what the sending socket is using.
after searching deep into the MSDN archives I found this helpful little page
https://msdn.microsoft.com/en-us/library/bb530747%28v=vs.85%29.aspx
hopefully this will add some insight to my problem. I will update on weather this resource ended up solving my problems
I'm trying to create a server socket with C++ in order to accept one client connection at a time. The program successfully creates the server socket and waits for incoming connections but when a connection is closed by the client the program would loop endlessly. Otherwise if the connection is interrupted it would keep waiting for new connections as expected. Any idea why this is happening? Thanks
This is my C++ server code:
int listenfd, connfd, n;
struct sockaddr_in servaddr, cliaddr;
socklen_t clilen;
pid_t childpid;
char mesg[1000];
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(32000);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 1024);
while (true) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
if ((childpid = fork()) == 0) {
close (listenfd);
while (true) {
n = recvfrom(connfd, mesg, 1000, 0, (struct sockaddr *)&cliaddr, &clilen);
sendto(connfd, mesg, n, 0, (struct sockaddr *)&cliaddr, sizeof(cliaddr));
mesg[n] = 0;
printf("%d: %s \n", n, mesg);
if (n <= 0) break;
}
close(connfd);
}
}
For some reason when the client closes the connection the program would keep printing -1: even with the if-break clause..
You never close connfd in parent process (when childpid != 0), and you do not properly terminate child process that will try to loop. Your if block should look like :
if ((childpid = fork()) == 0) {
...
close(connfd);
exit(0);
}
else {
close(connfd);
}
But as you say you want to accept one connection at a time, you can simply not fork.
And as seen in other answers :
do not use mesg[n] without testing n >= 0
recvfrom and sendto are overkill for TCP simply use recv and send (or even read and write)
mesg[n] = 0;
This breaks when n<0, ie. socket closed
The problem is your "n" and recvfrom. You are having a TCP client so the recvfrom won't return the correct value.
try to have a look on :
How to send and receive data socket TCP (C/C++)
Edit 1 :
Take note that you do the binding not connect() http://www.beej.us/guide/bgnet/output/html/multipage/recvman.html
means there is an error in recieving data, errno will be set accordingly, please try to check the error flag.
you've written a TCP server, but you use recvfrom and sendto which are specific for connection-less protocols (UDP).
try with recv and send. maybe that might help.
I'm working on UDP chat for programming classes. For now, I'm dealing with parallel in/out.
So, I'm creating thread to receive messages from server:
// in-thread
DWORD WINAPI in_thread(void* param)
{
int n; // variable receivefrom returned
char buff2[1000];
sockaddr_in client_addr;
int client_addr_size = sizeof(client_addr);
SOCKET my_sock;
my_sock = (SOCKET)param; // casting from void* to SOCKET
// reading server message
while (1)
{
n = recvfrom(my_sock, buff2, sizeof(buff2) - 1, 0, (sockaddr*)&client_addr, &client_addr_size);
// ......................
}
ExitThread(0);
}
And socket handle goes from:
hThread = CreateThread(NULL, NULL, &in_thread, (void*)sock, NULL, &ThreadId);
But I am recieving:
Error 10022: Invalid argument. (Returned by rercvfrom)
Where could it have gone wrong?
edit:
If it goes without passing to CreateThread, it works fine.
For example:
SOCKET sock;
// Opening socket
sock=socket(AF_INET, SOCK_DGRAM, 0);
int n; // variable receivefrom returned
char buff2[1000];
sockaddr_in client_addr;
int client_addr_size = sizeof(client_addr);
n= recvfrom(sock,buff2,sizeof(buff2)-1,0, (sockaddr *) &client_addr, &client_addr_size);
It works fine, socket works, no errors given, but when I pass it to createthread like in code in the question, error occures.
Using VS10, winsock2 lib.
'my_sock', and therefore 'param' and 'sock', is not a valid socket handle. Something wrong with your socket creation code.
I have a client application that sends TCP packets. Currently, my application does this:
creates a socket, binds and sends the packets.
struct sockaddr_in localaddress;
localaddress.sin_port = htons(0);
localaddress.sin_addr.s_addr = INADDR_ANY;
int socket;
socket = socket(AF_INET, SOCK_STREAM, 0));
bind(socket, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) );
And in another thread, the application connects and sends the packets:
struct socketaddr_in remoteaddress;
// omitted: code to set the remote address/ port etc...
nRet = connect (socket, (struct sockaddr * ) & remoteaddress, sizeof (sockaddr_in ));
if (nRet == -1)
nRet = WSAGetLastError();
if (nRet == WSAEWOULDBLOCK) {
int errorCode = 0;
socklen_t codeLen = sizeof(int);
int retVal = getsockopt(
socket, SOL_SOCKET, SO_ERROR, ( char * ) &errorCode, &codeLen );
if (errorCode == 0 && retVal != 0)
errorCode = errno;
}
/* if the connect succeeds, program calls a callback function to notify the socket is connected, which then calls send() */
Now I want to specify a port range for local port, so I changed the code to
nPortNumber = nPortLow;
localaddress.sin_port = htons(nPortNumber);
and loops nPortNumber in my port range, e.g ( 4000 - 5000 ) until the bind succeeds.
Since I always start my nPortNumber from the low port, if a socket is previously created on the same port, I get the WSAEADDRINUSE error as errorCode, which is too late for me because it has already passed the socket creation stage. (Why didn't I get WSAEADDRINUSE at bind() or connect()?)
Is there a way I can get the WSAEADDRINUSE earlier or is there a way to create a socket in the port range that binds and connects?
Thanks in advance!
I cannot answer with 100% certainty as for that I should know at which point you actually get WSAEADDRINUSE.
IN any case, it is normal you don't get it at bind, because you use INADDR_ANY. IIRC, this actually delays the bind process to the actual connect (my guess is it then changes the INADDR based on routing for the remote addr). However, as far as I know, you should then actually get the error at the call of connect...