我必须计算服务器接收的数字的平均值,然后在C中的TCP连接中将其发送到客户端。程序必须如下所示: 客户端向服务器发送带有号码的消息(例如):2 10 12 - > 2是数据的数量,10和12是数据。服务器接收数字并将它们的计数发送给客户端(在此示例中,计数为" 2")。它一直持续到客户端发送号码" 0"。此时,服务器必须向客户端发送一条消息,其中计算了数据的数量,并且在同一行中,它们的平均值。如果我发送" 2 10 12"服务器向客户端发送消息:" 4 8.25"。 " 4"是要计算的数据的数量和" 8.25"是平均的。
到目前为止,我为客户做了第一部分:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
int simpleSocket = 0;
int simplePort = 0;
int returnStatus= 0;
char buffsend[256];
char buffrecv[256];
char buff[256];
int i, n, length, ndata;
float average=0;
struct sockaddr_in simpleServer;
if (3 != argc) {
fprintf(stderr, "Usage: %s <server> <port>\n", argv[0]);
exit(1);
}
/* create a streaming socket */
simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (simpleSocket == -1) {
fprintf(stderr, "Could not create a socket!\n");
exit(1);
}
else {
fprintf(stderr, "Socket created!\n");
}
/* retrieve the port number for connecting */
simplePort = atoi(argv[2]);
/* setup the address structure */
/* use the IP address sent as an argument for the server address */
//bzero(&simpleServer, sizeof(simpleServer));
memset(&simpleServer, '\0', sizeof(simpleServer));
simpleServer.sin_family = AF_INET;
//inet_addr(argv[2], &simpleServer.sin_addr.s_addr);
simpleServer.sin_addr.s_addr=inet_addr(argv[1]);
simpleServer.sin_port = htons(simplePort);
/* connect to the address and port with our socket */
returnStatus = connect(simpleSocket, (struct sockaddr *)&simpleServer, sizeof(simpleServer));
if (returnStatus == 0) {
fprintf(stderr, "Connect successful!\n");
}
else {
fprintf(stderr, "Could not connect to address!\n");
close(simpleSocket);
exit(1);
}
/* get the message from the server */
do {
bzero(buffsend, 256);
printf("insert num dati or terminate(write '0'): ");
fgets(buffsend,256,stdin);
n=atoi(buffsend);
if(n>6) {
printf("Error\n");
}
else {
length=strlen(buffsend);
for(i=0;i<n;i++) {
printf("insert number: ");
length=strlen(buffsend);
buffsend[length-1]=' ';
fgets(buffsend+length,256-length,stdin);
write(simpleSocket, buffsend, strlen(buffsend));
read(simpleSocket, buffrecv, 256);
}
ndata=atoi(buffrecv);
printf("DT %d\n", ndata);
}
} while((n!=0) && (n>0));
close(simpleSocket);
return 0;
}
这适用于服务器:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int simpleSocket = 0;
int simplePort = 0;
int returnStatus = 0;
char buff[256];
char message[256];
int n, i, DT;
int count=0;
float average=0;
struct sockaddr_in simpleServer;
if (2 != argc) {
fprintf(stderr, "Usage: %s <port>\n", argv[0]);
exit(1);
}
simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (simpleSocket == -1) {
fprintf(stderr, "Could not create a socket!\n");
exit(1);
}
else {
fprintf(stderr, "Socket created!\n");
}
/* retrieve the port number for listening */
simplePort = atoi(argv[1]);
/* setup the address structure */
/* use INADDR_ANY to bind to all local addresses */
memset(&simpleServer, '\0', sizeof(simpleServer));
simpleServer.sin_family = AF_INET;
simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
simpleServer.sin_port = htons(simplePort);
/* bind to the address and port with our socket */
returnStatus = bind(simpleSocket,(struct sockaddr *)&simpleServer,sizeof(simpleServer));
if (returnStatus == 0) {
fprintf(stderr, "Bind completed!\n");
}
else {
fprintf(stderr, "Could not bind to address!\n");
close(simpleSocket);
exit(1);
}
/* lets listen on the socket for connections */
returnStatus = listen(simpleSocket, 5);
if (returnStatus == -1) {
fprintf(stderr, "Cannot listen on socket!\n");
close(simpleSocket);
exit(1);
}
while (1)
{
struct sockaddr_in clientName = { 0 };
int simpleChildSocket = 0;
int clientNameLength = sizeof(clientName);
/* wait here */
simpleChildSocket = accept(simpleSocket,(struct sockaddr *)&clientName, &clientNameLength);
if (simpleChildSocket == -1) {
fprintf(stderr, "Cannot accept connections!\n");
close(simpleSocket);
exit(1);
}
/* handle the new connection request */
/* write out our message to the client */
do {
read(simpleChildSocket, buff, 256);
num=atoi(buff);
conta++;
DT=(conta)-1;
DT=write(simpleChildSocket, buff, strlen(buff));
printf("Message received: %s\n", buff);
bzero(buff, 256);
} while(num!=0);
close(simpleChildSocket);
}
close(simpleSocket);
return 0;
}
答案 0 :(得分:0)
您的代码中有一些修复,尤其是在客户端。使用| size |发送包更方便|数据|立刻,比每个数字。
服务器端接收数据包,读取大小并累积,读取数据并累积,然后将大小发送给客户端。
如果客户端发送0,则服务器计算平均值并发送结果。 我相信它将成为最初的想法。
cliente side,main loop:
/*--------cliente side---------*/
int iResult;/*iResult >1 get from connect*/
char buffsend[256];
char szTmp[50];
do {
menset(buffsend,0,256);/*zero memory*/
menset(szTmp,0,50);/*zero memory*/
printf("insert num dati or terminate(write '0'): ");
fgets(szTmp,50,stdin);
int n = atoi(szTmp);
if(n>6)
printf("Error\n");
else
{
sprintf(buffsend,"%d ",n);
for(int h=0;h<n;h++)
{
printf("insert number: ");
fgets(szTmp,50,stdin);
szTmp[strcspn(szTmp, "\n")] = 0;/*<---remove end line */
strcat(buffsend,szTmp);/*concatenate new num*/
strcat(buffsend," ");/*add space*/
}
}
/*send the data <len><space><data> exemp: 2 12 34*/
iResult = write( ConnectSocket, buffsend, strlen(buffsend) );
if (iResult == -1)
{
printf("send failed with error: -1\n");
close(ConnectSocket);
return 1;
}
menset(buffsend,0,256);/*zero memory*/
iResult = read(ConnectSocket, buffsend, 256);
if ( iResult > 0 )
printf("Bytes received: %d > %s \n", iResult,recvbuf);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed with error: %d\n", WSAGetLastError());
} while( iResult > 0 );
服务器端循环:
/*-------------server side------------*/
int iResult;/*At this point iResult is greater than 0, by the return of connect*/
int nNumerator;
int den;/*Accumulate sizes*/
float faverage;
nNumerator=0;
den = 0;
faverage=0;
do
{
memset(recvbuf,0,256);
iResult = read(ClientSocket, recvbuf, recvbuflen);
if (iResult > 0)
{
char bufftmp[25];
int numpart;
int iTmp;
numpart =0;
iTmp =0;
memset(bufftmp,0,25);
printf("Bytes received: %d\n", iResult);
printf("%s\n",recvbuf);
/*Traverses all received datar ecvbuf and separates the accumulating size into den,
and then accumulates the data in nNumerator*/
for(int k=0;k<iResult;k++)
{
bufftmp[iTmp++]=recvbuf[k];
if(recvbuf[k]==' ')
{
if(!numpart)/*is numpart zero*/
{
bufftmp[iTmp]='\0';//make space null
numpart=atoi(bufftmp);
den+=numpart;/*acumalate to average*/
printf("lenght: %d\n",numpart);/*get only length*/
memset(bufftmp,0,25);
if(numpart==0)
{
/*go to average*/
faverage = (float)nNumerator/(float)den;
}
}
else/* if numparte > 0 get data*/
{
bufftmp[iTmp]='\0';
printf("%s ",bufftmp);
nNumerator+=atoi(bufftmp);/*save in to buffer of int´s*/
memset(bufftmp,0,25);
}
iTmp=0;
printf("\n");
}
}
memset(recvbuf,0,256);
if(numpart)/*if not zero, send length of data to client*/
sprintf(recvbuf,"%d",numpart);
else/*if not, send average*/
sprintf(recvbuf,"%d %f",den,faverage);
iResult = write( ClientSocket, recvbuf, strlen(recvbuf));
if (iResult == -1)
{
printf("send failed with error: -1\n");
close(ClientSocket);
return 1;
}
}
else if (iResult == 0)
printf("Connection closing...\n");
else
{
printf("recv failed with error: -1\n");
close(ClientSocket);
return 1;
}
}while (iResult > 0);