Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 12
  1. #1

    socket multiconnessione

    Ciao a tutti, avrei bisogno di sapere come si può fare in modo che creato un server con c++ e le winsock, sia possibile effettuare più connessioni allo stesso server da parte di un numero non definito di client. Se cortesemente qualcuno può postarmi il codice del server e del client lo rigrazio in anticipo.


    grazie ancora


    ciao

  2. #2
    Moderatore di Programmazione L'avatar di alka
    Registrato dal
    Oct 2001
    residenza
    Reggio Emilia
    Messaggi
    24,301

    Moderazione

    Come indicato nel Regolamento, il linguaggio di programmazione di riferimento va specificato anche nel titolo della discussione.

    Il titolo di questa discussione lo modifico io.

    Ciao!
    MARCO BREVEGLIERI
    Software and Web Developer, Teacher and Consultant

    Home | Blog | Delphi Podcast | Twitch | Altro...

  3. #3
    ok, grazie

  4. #4
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    in c si una una select(), in c++

  5. #5
    Non è che potresti postare il codice anche in C ? per me non cambia molto

    grazie mille

  6. #6
    Utente di HTML.it L'avatar di floyd
    Registrato dal
    Apr 2001
    Messaggi
    3,837
    qui è implementato un server che accetta molti client sulla stessa porta

  7. #7
    thank you, dò un'occhiata e cerco di fare qualcosa

    ciao

  8. #8
    se ti interessa io avevo fatto questo qualche settimana fa, poi ho abbandonato tutto x la maturità e lo migliorerò in seguito
    in pratica creca le connessioni e spedisce i msg ricevuti a tutti gli utenti connessi
    codice:
    #include <iostream>
    #include "winsock2.h"
    #include <string.h>
    #define MAXmsg 100
    #define MAXusr 100
    using namespace std;
    typedef struct {
            char name[20];
            SOCKET socket;
    } user;
    
    int main() {
         WSADATA wsaData;
         if ( WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR )
               cout<<"Error at WSAStartup()\n";
         SOCKET Socket;
         Socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
         if ( Socket == INVALID_SOCKET )
            {     
               cout<<"Error at socket():"<<WSAGetLastError()<<"\n";
               WSACleanup();
               return 1;}
         sockaddr_in service;
         service.sin_family = AF_INET;
         service.sin_addr.s_addr = inet_addr( "127.0.0.1" );
         service.sin_port = htons( 27015 );
         if ( bind( Socket, (SOCKADDR*) &service, sizeof(service) ) == SOCKET_ERROR ) {
               cout<<"bind() failed.\n";
               closesocket(Socket);
               return 1;}
        //Listening on Socket
        listen( Socket, MAXusr );
        user utenti[MAXusr];
        int usr=0,z,j;
        long unsigned ioctl=1;   
        char sendbuf[MAXmsg] = "Server: Sending Data.";
        char recvbuf[MAXmsg] = "";
        ioctlsocket (Socket, FIONBIO, &ioctl);
        while(1)
        {
        if((utenti[usr].socket=accept( Socket, NULL, NULL ))!=INVALID_SOCKET)
        {      ioctlsocket (utenti[usr].socket, FIONBIO, &ioctl);
               recv(utenti[usr].socket,utenti[usr].name,20, 0 );
               cout<<"client "<<usr+1<<" connected as "<<utenti[usr].name<<"\n";
               usr++;
               }
        //Sending and Receiving Data
        for(z=0;z<MAXmsg;z++)
                recvbuf[z]='\0';
        //controllo tutti i client x msg
        for(z=0;z<usr;z++)
        {
               if(recv( utenti[z].socket, recvbuf, MAXmsg, 0 )!=0)
                 for(j=0;j<usr;j++)
                 {if(j!=z)
                       send( utenti[j].socket, recvbuf, strlen(recvbuf), 0 );}
        }
        }
        WSACleanup();
        system("PAUSE");
        return 0;
    }

  9. #9
    ok, grazie. Provo anche con il tuo codice

  10. #10
    Utente di HTML.it
    Registrato dal
    Dec 2003
    Messaggi
    423
    Secondo me, anche per separare le varie sezioni, ti conviene usare un pò di multithreading. Ovvero, ti fai una bella struct che comprende un thread ed un socket (ed anche un nome magari). Poi metti un thread che sta sempre in listen ed avvia gli altri thread di comunicazione man mano che i client fanno richieste. Così hai un programma un pò più strutturato e gestibile (IMHO).
    Per capirci, tipo così:
    codice:
    #define WINDOWS_LEAN_AND_MEAN
    #include <windows.h>
    #include "winsock2.h"
    using namespace std;
    
    struct client
    {
    	char ID[20];
    	SOCKET sock;
    	HANDLE Thread;
    } clients[80];
    
    int FindFirstFree()
    {
    	for(int i = 0; i < 80; i++)
    	{
    		if (!clients[i].sock) return i;
    	}
    }
    
    #include <time.h>
    char *GiveID()
    {
    	srand(time(0) + clock());
    	char *result = new char[20];
    	for (int i = 0; i < 19; i++) result[i] = rand()%26 + 65;
    	result[19] = '\0';
    	return result;
    	/*Come esempio ho messo un generatore di stringhe random, ma puoi metterci qualunque cosa*/
    }	 
    
    SOCKET listening, incoming;
    bool uscita = false; // Quando vuoi uscire, setti questa variabile a 1
    
    DWORD ClientThread(int c);
    
    DWORD Listening(LPDWORD NotUsed)
    {
    	listening = socket(AF_INET, SOCK_STREAM, 0);
    	sockaddr_in addr;
    
    	addr.sin_family = AF_INET;
    	addr.sin_port = htons(4015);
    	addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    	
    	bind(listening, (SOCKADDR*)&addr, sizeof(addr));
    	
    	listen(listening, 10);
    	
    	incoming = SOCKET_ERROR;
    	while(1) 
    	{
    		incoming = accept(listening, NULL, NULL);
    		if (incoming != SOCKET_ERROR)
    		{
    			int c = FindFirstFree();
    			strcpy(clients[c].ID, GiveID());
    			clients[c].sock = incoming;
    			clients[c].Thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) ClientThread(c), NULL, 0, NULL);
    		}
    	}
    }
    
    DWORD ClientThread(int c)
    {
    	//Qui fai quello che vuoi col tuo client ! Il valore c, passato alla funzione ti indica chi è il client di questo thread.
    }
    	
    int main()
    {
    	WSADATA wsadata;
    	
    	WSAStartup(MAKEWORD(2,2), &wsadata);
    
    	CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) Listening, NULL, 0, NULL);
    	
    	while(!uscita);
    	
    	WSACleanup();
    }
    Fondamentalmente è molto simile al codice di suomi, però fatto coi thread .

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.