Torna indietro   Hardware Upgrade Forum > Software > Programmazione

Oracle AI World 2026: in Europa prima la sovranità, poi la sicurezza e solo dopo l'IA
Oracle AI World 2026: in Europa prima la sovranità, poi la sicurezza e solo dopo l'IA
In tre giorni a Las Vegas Oracle ha presentato agenti che eseguono il lavoro, l'alleanza con OpenAI e un cloud aperto agli acceleratori di tutti. Ma i clienti europei chiedono garanzie prima ancora delle funzionalità
DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort
DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort
Fino a 740 km WLTP con la batteria da 97,2 kWh, sospensioni che leggono la strada con una telecamera e un abitacolo da salotto parigino. La nuova DS N°7 raccoglie l'eredità della DS 7 e la porta, per la prima volta, nel mondo 100% elettrico. Ecco come è fatta, cosa offre e quanto costa.
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più
Abbiamo provato Samsung Galaxy Tab S12 Ultra nella versione 12 GB + 256 GB con tastiera, e il risultato è un tablet che in questa configurazione si comporta come un notebook con la fluidità tipica di Android. Spessore di 5,1 mm, display Dynamic AMOLED 2X da 14,6 pollici, MediaTek Dimensity 9500 e un software senza incertezze compongono un prodotto di vertice, con prezzi da 1.539 euro, frenato solo da un'autonomia nella parte bassa del confronto
Tutti gli articoli Tutte le news

Vai al Forum
Rispondi
 
Strumenti
Old 27-09-2004, 11:27   #1
Rigo007
Member
 
L'Avatar di Rigo007
 
Iscritto dal: Oct 2001
Città: Trento
Messaggi: 164
echo server/client UDP in MVC++

ciao! Devo fare un echo server e un client ke comunicano tra loro usando il protocollo UDP!
Questo protocollo usa le funzioni sendto() e recvfrom()...
Io ho scritto questo codice...qualcuno riesce a sistemarmelo utilizzando tali funzioni?
Ho inserito nel codice dei commenti e degli esempi ke potrebbero essere utili (o fastidiosi), vedete vuoi!

Thank you...anticipatamente!

Nb. per compilare dovete inserire nel linker la libreria wsock32.lib
Rigo007 è offline   Rispondi citando il messaggio o parte di esso
Old 27-09-2004, 11:29   #2
Rigo007
Member
 
L'Avatar di Rigo007
 
Iscritto dal: Oct 2001
Città: Trento
Messaggi: 164
// UDP client using Winsock 2.0

#include <winsock2.h>
#include <stdlib.h>
//#include <string.h>
#include <stdio.h>
#include <conio.h>
//#include <iostream.h>

#include <string>
#include <iostream>

using namespace std ;



#define DEFAULT_PORT 5001

int main() {
char Buffer[128];
char *server_name = "localhost";
unsigned short port = DEFAULT_PORT;

//
char ch;
string s;
//

int err;
int retval;
int loopflag = 0;
int loopcount;
int maxloop = -1;
unsigned int addr;
struct sockaddr_in server;
struct hostent *hp;
WSADATA wsaData;
WORD wVersionRequested;

SOCKET conn_sock;

wVersionRequested = MAKEWORD(2,0); // creo la variabile che contiene la versione della wsock32.dll (winsock ver 2.0)

err = WSAStartup(wVersionRequested,&wsaData); // inizializzo la wsock32.dll

if(err != 0) {
printf(" Nessuna winsock trovata!\n");
fprintf(stderr,"WSAStartup failed with error %d\n",WSAGetLastError());
WSACleanup();
return(-1);
} else
printf(" Vers$ %d \n nHVer$ %d \n nMaxSock %d \n nMaxUdpDg %d \n Description: %s\n Status: %s\n\n",
wsaData.wVersion,
wsaData.wHighVersion,
wsaData.iMaxSockets,
wsaData.iMaxUdpDg,
wsaData.szDescription,
wsaData.szSystemStatus);

printf(" --> CLIENT UDP <--\n\n");

/*
Attempt to detect if we should call gethostbyname() or gethostbyaddr()
*/

if(isalpha(server_name[0])) { // server address is a name
hp = gethostbyname(server_name);
} else { // convert nnn.nnn address to a usable one
addr = inet_addr(server_name);
hp = gethostbyaddr((char *)&addr,4,AF_INET);
}

if(hp == NULL) {
fprintf(stderr," Client --> Cannot resolve address [%s] : Error %d\n",
server_name,WSAGetLastError());
WSACleanup();
exit(1);
}

// Copy the resolved information into the sockaddr_in structure

memset(&server,0,sizeof(server));
memcpy((&server.sin_addr),hp->h_addr,hp->h_length);
server.sin_family = hp->h_addrtype;
server.sin_port = htons(port);

conn_sock = socket(AF_INET,SOCK_DGRAM,0);

if(conn_sock< 0) {
fprintf(stderr," Client --> Error opening socket : Error %d\n",WSAGetLastError());
WSACleanup();
return(-1);
}

/*
Notice that nothing in this code is specific to whether we
are using UDP or TCP.
We achieve this by using a simple trick.
When connect() is called on a datagram socket, it does not
actually establish the connection as a stream (TCP) socket
would. Instead, TCP/IP establishes the remote half of the
(LocalIPAddress, LocalPort, RemoteIP, RemotePort) mapping.
This enables us to use send() and recv() on datagram sockets,
instead of recvfrom() and sendto()
*/

printf(" Client connecting to: %s\n",hp->h_name);

// while(ch != 0x1b) {
// ch = getchar();
// getline(cin,s,'\n');
// err = sendto(conn_sock,&ch,sizeof(Buffer),0,(struct sockaddr *)&server,sizeof(struct sockaddr));
// }

err = sendto(conn_sock,Buffer,sizeof(Buffer),0,(struct sockaddr *)&server,sizeof(struct sockaddr));

if(err == SOCKET_ERROR) {
fprintf(stderr," sendto() failed: %d\n",WSAGetLastError());
WSACleanup();
return(-1);
}


// --------------------------------------------------------------------------------

/*

ESEMPIO SOTTO LINUX

if((numbytes=sendto(sockfd, argv[2], strlen(argv[2]), 0,
(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) {
perror("sendto");
exit(1);
}
printf("sent %d bytes to %s\n", numbytes,
inet_ntoa(their_addr.sin_addr));

/*
FUNZIONE SENDTO()

int sendto(SOCKET s,const char FAR * buf,int len,int flags,const struct sockaddr FAR * to,int tolen);

Parameters:
s
[in] A descriptor identifying a (possibly connected) socket.
buf
[in] A buffer containing the data to be transmitted.
len
[in] The length of the data in buf.
flags
[in] An indicator specifying the way in which the call is made.
to
[in] An optional pointer to the address of the target socket.
tolen
[in] The size of the address in to.

*/
/*
ESEMPIO con FTP protocol

char mess[100]; // il messaggio inviato dal Server (max 100 byte);
int n = 0;

n = recv(miosock,mess,100,0); // si riceve il messaggio di benvenuto dal Server

mess[n] = 0; // n rappresenta la lunghezza del messaggio in arrivo (max 100 byte)
printf(mess); // lo visualizzo

while(ch != 0x1b) { // finchè ch è diverso da ESC
ch = getchar(); // aspetto un carattere
send(miosock,&ch,1,0); // e lo invio al Server
}


/*

while(ch!=0x1b) { // finchè ch è diverso dal tasto ESC
ch = getchar(); // aspetto un carattere
send(miosock,&ch,1,0); // e lo invio al Server
}


// */

// ----------------------------------------------------------------------------------------------------------

/*
if(connect(conn_sock,(struct sockaddr*)&server,sizeof(server)) == SOCKET_ERROR) {
fprintf(stderr," connect() failed: %d\n",WSAGetLastError());
WSACleanup();
return(-1);
}
*/

// cook up a string to send

loopcount = 0;

while(1) {

wsprintf(Buffer," This is a small message [number %d]",loopcount++);
retval = send(conn_sock,Buffer,sizeof(Buffer),0);

if(retval == SOCKET_ERROR) {
fprintf(stderr," send() failed: error %d\n",WSAGetLastError());
WSACleanup();
return -1;
}

printf(" Sent Data [%s]\n",Buffer);

retval = recv(conn_sock,Buffer,sizeof(Buffer),0);

if (retval == SOCKET_ERROR) {
fprintf(stderr," recv() failed: error %d\n",WSAGetLastError());
closesocket(conn_sock);
WSACleanup();
return -1;
}

/*
We are not likely to see this with UDP, since there is no
'connection' established.
*/

if (retval == 0) {
printf(" Server closed connection\n");
closesocket(conn_sock);
WSACleanup();
return -1;
}

printf(" Received %d bytes, data [%s] from server\n",retval,Buffer);

if(!loopflag) {
printf(" Terminating connection\n");
break;
}
else {
if ( (loopcount >= maxloop) && (maxloop >0) )
break;
}
}

closesocket(conn_sock);
WSACleanup();
getch();

return(0);

}
Rigo007 è offline   Rispondi citando il messaggio o parte di esso
Old 27-09-2004, 11:30   #3
Rigo007
Member
 
L'Avatar di Rigo007
 
Iscritto dal: Oct 2001
Città: Trento
Messaggi: 164
/*
Simple UDP server using Winsock 2.0
*/

#include <winsock2.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define DEFAULT_PORT 5001

int main() {

char Buffer[128];
unsigned short port = DEFAULT_PORT;
int retval;
int fromlen;
int err;
struct sockaddr_in local,from;
WSADATA wsaData; // variabile che contiene i parametri di WSAStartup()
WORD wVersionRequested;

wVersionRequested = MAKEWORD(2,0); // creo la variabile che contiene la versione della wsock32.dll (winsock ver 2.0)

err = WSAStartup(wVersionRequested,&wsaData); // inizializzo la wsock32.dll

printf(" --> SERVER UDP <--\n\n");

if(err != 0) {
printf(" Nessuna winsock trovata!\n");
exit(1);
} else
printf(" Vers$ %d \n nHVer$ %d \n nMaxSock %d \n nMaxUdpDg %d \n Description: %s\n Status: %s\n\n",
wsaData.wVersion,
wsaData.wHighVersion,
wsaData.iMaxSockets,
wsaData.iMaxUdpDg,
wsaData.szDescription,
wsaData.szSystemStatus);

/*
Il codice soprastante serve per inizializzare la wsock32.dll, tramite la funzione WSAStartup()
che è specifica di Windows; le vengono passate come argomenti la versione di libreria richiesta
e l'indirizzo ad una struttura WSAData, che verrà riempita dalla WSAStartup con informazioni
relative alla libreria stessa.
In caso di errore la WSAStartup ritorna un codice diverso da 0 che stà ad indicare l'errore in questione
(fai riferimento al file winsock.h per la lista dei #define).
Il prefisso WSA stà ad indicare Windows Socket API.
*/

SOCKET listen_socket ,msgsock;

local.sin_family = AF_INET;
local.sin_addr.s_addr = INADDR_ANY;

// Port must be in Network Byte Order

local.sin_port = htons(port);

listen_socket = socket(AF_INET,SOCK_DGRAM,0);

if(listen_socket == INVALID_SOCKET) {
fprintf(stderr," socket() failed with error %d\n",WSAGetLastError()); // scrivo su file
WSACleanup();
return(-1);
}

/*
bind() associates a local address and port combination with the
socket just created. This is most useful when the application is a
server that has a well-known port that clients know about in advance.
*/

err = bind(listen_socket,(struct sockaddr*)&local,sizeof(local));

if(err == SOCKET_ERROR) {
fprintf(stderr," bind() failed with error %d\n",WSAGetLastError());
WSACleanup();
return(-1);
}

printf(" --> 'Listening' on port %d, protocol UDP\n",port);

while(1) {

fromlen = sizeof(from);

msgsock = listen_socket;

/*
for SOCK_DGRAM (UDP), the server will do
recvfrom() and sendto() in a loop.
*/

retval = recvfrom(msgsock,Buffer,sizeof(Buffer),0,(struct sockaddr*)&from,&fromlen);
printf(" Received datagram from %s\n",inet_ntoa(from.sin_addr));

if(retval == SOCKET_ERROR) {
fprintf(stderr," recvfrom() failed with error %d\n",WSAGetLastError());
closesocket(msgsock);
continue;
}
if(retval == 0) {
printf( " Client closed connection\n");
closesocket(msgsock);
continue;
}

printf(" Received %d bytes, data [%s] from client\n",retval,Buffer);

printf(" Echoing same data back to client\n");

retval = sendto(msgsock,Buffer,sizeof(Buffer),0,(struct sockaddr*)&from,fromlen);

if(retval == SOCKET_ERROR) {
fprintf(stderr," sendto() failed with error %d\n",WSAGetLastError());
}

printf(" UDP server looping back for more requests\n");

continue;
}
}
Rigo007 è offline   Rispondi citando il messaggio o parte di esso
 Rispondi


Oracle AI World 2026: in Europa prima la sovranità, poi la sicurezza e solo dopo l'IA Oracle AI World 2026: in Europa prima la sovrani...
DS N°7 E-Tense: il SUV premium made in Melfi che punta su autonomia e comfort DS N°7 E-Tense: il SUV premium made in Melfi...
Recensione Samsung Galaxy Tab S12 Ultra: non chiamatelo tablet... è molto di più Recensione Samsung Galaxy Tab S12 Ultra: non chi...
Hyundai IONIQ 5 N, l'elettrica che finge di essere termica (e ci riesce da paura) Hyundai IONIQ 5 N, l'elettrica che finge di esse...
CES Unveiled Milan, l'IA diventa tecnologia fondativa e il commercio torna centrale CES Unveiled Milan, l'IA diventa tecnologia fond...
Alphabet perde 500 miliardi di dollari i...
Reddit cambia strategia dopo il calo del...
Calcolo quantistico, Intel annuncia l'ac...
DirectX Raytracing si aggiorna: pi&ugrav...
Honda lancerà nuovamente il proto...
La prima missione Amazon Leo con il razz...
Invia il tuo nome su Titano, la luna di ...
Starship: Ship 42 e Super Heavy Booster ...
Chrome, meno tab switching con la nuova ...
L'IA agentica spopola fra le aziende, ma...
ASUS UGen300 arriva in Italia a 299 euro...
Iliad aggiorna la gamma di offerte per I...
Stop ai social per i minori, perché Brux...
Google Chrome integra Gemini in Enhanced...
Meta lancia Waddle World e Style Sketch,...
Chromium
GPU-Z
OCCT
LibreOffice Portable
Opera One Portable
Opera One 106
CCleaner Portable
CCleaner Standard
Cpu-Z
Driver NVIDIA GeForce 546.65 WHQL
SmartFTP
Trillian
Google Chrome Portable
Google Chrome 120
VirtualBox
Tutti gli articoli Tutte le news Tutti i download

Strumenti

Regole
Non Puoi aprire nuove discussioni
Non Puoi rispondere ai messaggi
Non Puoi allegare file
Non Puoi modificare i tuoi messaggi

Il codice vB è On
Le Faccine sono On
Il codice [IMG] è On
Il codice HTML è Off
Vai al Forum


Tutti gli orari sono GMT +1. Ora sono le: 08:14.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2026, Jelsoft Enterprises Ltd.
Served by www3v