logo
down
shadow

Socket recv() one byte at a time


Socket recv() one byte at a time

Content Index :

Socket recv() one byte at a time
Tag : cpp , By : richardD
Date : November 28 2020, 09:01 AM

seems to work fine Calling recv() one byte at a time will negatively impact performance. There is a certain amount of overhead on each call -- the transition to kernel mode, file descriptor lookup, dispatch to the protocol-specific driver, buffer/queue locking, etc. Calling recv() with larger buffers greatly decreases the average overhead per byte.

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Why Should I Set a Conservative Max Byte Size on a Socket's 'recv' Method?


Tag : cpp , By : Tony Siu
Date : March 29 2020, 07:55 AM
it should still fix some issue I am building a client using Python's socket.socket class that receives data which varies in size (usually between 500 and 5,000 bytes but it is theoretically possible for the client socket to receive 500,000 bytes). I am also writing the server that will communicate with this client socket. , All you're doing is wasting memory on an epic scale.

Socket C handle recv() and send() at the same time


Tag : c , By : davidg
Date : March 29 2020, 07:55 AM
hop of those help? As stated in comments, your server does nothing until recv() returns zero or -1, which mean the client has disconnected or aborted the connection respectively. As your client does neither of those things, you have an application-induced deadlock.

Python IRC ChatBot hangs on socket.recv after seemingly random time even though socket.settimeout is 8


Tag : python , By : picamiolo
Date : March 29 2020, 07:55 AM
should help you out Hey so I decided to create an IRC ChatBot whose sole purpose it is to read incoming messages from Twitch Chat and if a giveaway is recognized by a keyword it's supposed to enter the giveaway by sending !enter in Chat. , I think you've missunderstood how timeout work on the socket.
s.settimeout(8.0)
import select
ready = select.select([s], [], [], timeout_in_seconds)
if ready[0]:
    data = s.recv(1024)
from select import epoll, EPOLLIN
poll = epoll()
poll.register(s.fileno(), EPOLLIN)

events = poll.poll(1) # 1 sec timeout
for fileno, event in events:
    if event is EPOLLIN and fileno == s.fileno():
        data = s.recv(1024)

WINDOWS C: TCP Socket send&recv at the same time


Tag : c , By : Andrew
Date : March 29 2020, 07:55 AM
This might help you You don't need to open/connect 2 separate listening ports in order to implementing bi-directional communication. TCP is bi-directional, you only need one connection. However, you are enabling non-blocking socket I/O on both ends, but you are not actually using non-blocking I/O correctly. In particular, you are not handling the WSAEWOULDBLOCK error code at all, which is reported by recv() when there is no data available to read, and by send() when the receiver has too much data to read and cannot receive new data yet.
If you want to use threads, then use separate threads for reading and sending, and forget non-blocking I/O altogether. But make sure you are defining your threads correctly (you thread procedure is missing a required input parameter!).
#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <conio.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

DWORD WINAPI sendThrd(LPVOID lpParam)
{
    SOCKET sock = * (SOCKET*) lpParam;
    char smesg[155], *pdata;
    int len, ret;

    do
    {
        if (!fgets(smesg, sizeof(smesg), stdin))
            break;

        len = strlen(smesg);
        pdata = smesg;

        while (len > 0)
        {
            ret = send(sock, pdata, len, 0);
            if (ret == SOCKET_ERROR)
            {
                printf("Send failed. Error: %d", WSAGetLastError());
                break;
            }
            pdata += ret;
            len -= ret;
        }
    }
    while (true);

    shutdown(sock, SD_SEND);
    return 0;
}

DWORD WINAPI recvThrd(LPVOID lpParam)
{
    SOCKET sock = * (SOCKET*) lpParam;
    char smesg[256];
    int ret;

    FILE *fp = fopen("fout.txt", "w+");

    do
    {
        ret = recv(sock, smesg, sizeof(smesg), 0);
        if (ret <= 0)
        {
            if (ret == 0)
                printf("Client disconnected\n");
            else
                printf("Connection lost! Error: %d\n", WSAGetLastError());
            break;
        }

        printf("%.*s", ret, smesg);

        if (fp)
            fprintf(fp, "%.*s", ret, smesg);        
    }
    while (true);

    if (fp)
        fclose(fp);

    shutdown(sock, SD_RECEIVE);
    return 0;
}

int main()
{
    WSADATA wsa;
    SOCKET sock, newsock;
    int c;
    struct sockaddr_in server;

    printf("Initializing Winsock...\n");
    int ret = WSAStartup(MAKEWORD(2, 2), &wsa);
    if (ret != 0)
    {
        printf("Initialization Failed. Error: %d", ret);
        return 1;
    }
    printf("Initialized.\n");

    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d\n", WSAGetLastError());
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(3939);

    //bind
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Bind failed! Error: %d\n", WSAGetLastError());
        closesocket(sock);
        return 1;
    }
    printf("Binded!\n");

    // listen
    if (listen(sock, 1) == SOCKET_ERROR) {
        printf("Listen failed! Error: %d\n", WSAGetLastError());
        closesocket(sock);
        return 1;
    }
    printf("Now Listening...\n");

    //Accept!
    c = sizeof(client);
    newsock = accept(sock, (struct sockaddr *)&client, &c);
    if (newsock == INVALID_SOCKET) {
        printf("Couldn't Accept connection! Error: %d\n", WSAGetLastError());
        closesocket(sock);
        return 1;
    }

    //char *client_ip = inet_ntoa(client.sin_addr);
    //int client_port = ntohs(client.sin_port);
    printf("Accepted Connection!\n");

    printf("Starting Reader/Writer Threads...\n");
    HANDLE threads[2];
    threads[0] = CreateThread(NULL, 0, sendThrd, &newsock, 0, NULL);
    threads[1] = CreateThread(NULL, 0, recvThrd, &newsock, 0, NULL);

    WaitForMultipleObjects(2, threads, TRUE, INFINITE);

    CloseHandle(threads[0]);
    CloseHandle(threads[1]);

    closesocket(newsock);
    closesocket(sock);

    return 0;
}
#include "stdafx.h"
#include <stdio.h>
#include <winsock.h>
#include <stdlib.h>
#include <conio.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

DWORD WINAPI sendThrd(LPVOID lpParam)
{
    SOCKET sock = * (SOCKET*) lpParam;
    char smesg[155], *pdata;
    int len, ret;

    do
    {
        if (!fgets(smesg, sizeof(smesg), stdin))
            break;

        len = strlen(smesg);
        pdata = smesg;

        while (len > 0)
        {
            ret = send(sock, pdata, len, 0);
            if (ret == SOCKET_ERROR)
            {
                printf("Send failed. Error: %d\n", WSAGetLastError());
                break;
            }
            pdata += ret;
            len -= ret;
        }
    }
    while (true);

    shutdown(sock, SD_SEND);
    return 0;
}

DWORD WINAPI recvThrd(LPVOID lpParam)
{
    SOCKET sock = * (SOCKET*) lpParam;
    char smesg[256];
    int ret;

    do
    {
        ret = recv(sock, smesg, sizeof(smesg), 0);
        if (ret <= 0)
        {
            if (ret == 0)
                printf("Server disconnected\n");
            else
                printf("Connection lost! Error: %d\n", WSAGetLastError());
            break;
        }

        printf("%.*s", ret, smesg);
    }
    while (true);

    shutdown(sock, SD_RECEIVE);
    return 0;
}

int main(int argc, char *argv[])
{
    WSADATA wsa;
    SOCKET sock;
    struct sockaddr_in server;

    printf("Initializing Winsock...\n");
    int ret = WSAStartup(MAKEWORD(2, 2), &wsa);
    if (ret != 0)
    {
        printf("Initialization Failed. Error: %d", ret);
        return 1;
    }
    printf("Initialized.\n");

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock == INVALID_SOCKET) {
        printf("Could not create socket! Error: %d", WSAGetLastError());
        getch();
        return 1;
    }
    //textcolor(2);
    printf("Socket Created!\n");

    memset(&server, 0, sizeof(server));
    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons(3939);

    //Connect
    if (connect(sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
        printf("Connect failed! Error: %d", WSAGetLastError());
        closesocket(sock);
        getch();
        return 1;
    }
    printf("Connected\n");

    //Creating reader/writer threads.

    printf("Starting Reader/Writer Threads...\n");
    HANDLE threads[2];
    threads[0] = CreateThread(NULL, 0, sendThrd, &sock, 0, NULL);
    threads[1] = CreateThread(NULL, 0, recvThrd, &sock, 0, NULL);

    WaitForMultipleObjects(2, threads, TRUE, INFINITE);

    CloseHandle(threads[0]);
    CloseHandle(threads[1]);

    closesocket(sock);

    getch();
    return 0;
}

python byte to int[] from socket.recv


Tag : python , By : user152423
Date : March 29 2020, 07:55 AM
To fix the issue you can do List comprehension (see: https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions) would seem to be the correct course of action, to "convert":
data = [ord(i) for i in data]
data = [ord(i) for i in sock.recv(1024)]
Related Posts Related QUESTIONS :
  • what happened if an exception is not captured?
  • Redundant naming in C/C++ typedefs/structs
  • question about STL thread-safe and STL debugging
  • killing a separate thread having a socket
  • Returning the size of available virtual memory at run-time in C++
  • Parallel computing for integrals
  • How do I force my std::map to deallocate memory used?
  • C++ Templates: implicit conversion, no matching function for call to ctor
  • Adding python script to c++ project
  • C++ private pointer "leaking"?
  • Initializing Primitive Array to One Value
  • how is push_back implemented in STL vector?
  • C++ Profiling: KiFastSystemCallRet
  • Multiple rows with a single INSERT in SQLServer 2008
  • Use super class's address/pointer in initialization list
  • double fork using vfork
  • Convert char pointer (char*) to struct
  • Does anyone have good tips for using pc-lint?
  • C++ How fast is passing around objects?
  • template type's ctor arguments at instantiation time
  • Get list of windows in taskbar on Windows 7?
  • Curl connection options
  • Best cross-platform solution for network server?
  • simple c++ file opening issue
  • Switching from C++ (with a lot of STL use) to C for interpreter building
  • How can I access the JPEG image pixels as a 3D array like we do in MATLAB?
  • What wording in the C++ standard allows static_cast<non-void-type*>(malloc(N)); to work?
  • Avoid allocating in constructor or preserve simplicity (and RAII?)
  • Can C++ raise an error when std array initialization is too small?
  • Reference to end is ambiguous
  • Problem with basic usage of std::enable_if
  • How to print out a decimal number as octal number using setiosflags in C++
  • Open Visual Studio with solution and specific file and line
  • Enum value based on template type
  • Is there any way to swap nodes in std::list?
  • How to copy QString into wchar_t buffer
  • Make the compiler generate an empty default function for an std::function
  • Insert or push_back to end of a std::vector?
  • Best practice for const temporary types
  • Include CSV File in Complied Binary
  • Issue with binding non static function to callback
  • How can read from some files and write content of them with different form into files with same names
  • Why does auto deduce this variable as double and not float?
  • no instance of overloaded function "std::make_unique" matches the argument list, but works with unique_ptr con
  • How to see array size from a pointer in c++
  • Error taking address of temporary in Eclipse
  • Using an iterator to go through a vector and modify the contents
  • Are extern extern "C", and extern "C" extern, allowed?
  • Can't solve C2660 and C2065 Errors
  • C referencing C++ extern
  • How to write the definition of a derived class in c++?
  • Why when I include <cmath> I need to use the namespace std too?
  • How to assign a 32-bit unsigned integer to a bit field containing 32 bits
  • Why does the same class being defined in multiple .cpp files not cause a linker multiple definition error?
  • C++ 11db error when trying to quit the program in xcode. beginner level
  • Add content of a vector into a Capnproto map object
  • Recursively Pass Template Template To a Template Template Function
  • Swap rows in a 2D array with std::swap. How does it work?
  • Is there any situation in which an object's storage might change during its lifetime?
  • clang++ always generates empty profraw coverage reports
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com