Demo entry 6516624

dataserver

   

Submitted by anonymous on May 31, 2017 at 08:40
Language: C++. Code size: 2.1 kB.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    struct sockaddr_in server, client;
    int socketfd, connectfd, port;
    int sin_size;

    // transform parameters
    if (argc != 3) {
        cout << "Please use this as the following format:\n" << argv[0] << " IP port\n";
        exit(1);
    }
    port = atoi(argv[2]);
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(argv[1]);

    // create socket
    socketfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (socketfd < 0) {
        cout << "socket creating error!\n";
        exit(1);
    }
    // bind address and port
    struct sockaddr * myaddr = (struct sockaddr *)&server;
    if (::bind(socketfd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1) {
        cout << "bind failed\n";
        exit(2);
    }
    // listen3
    if (listen(socketfd, 1) == -1) {
        cout << "listen() failed\n";
        exit(3);
    }
    // acceptn
    sin_size = sizeof(struct sockaddr_in);
    if((connectfd = accept(socketfd, (struct sockaddr *)&client, (socklen_t *)&sin_size)) == -1){
        cout << "accept() failed\n";
        exit(4);
    }

    // receive data
    int col, row, i, j;

    recv(connectfd, &col, sizeof(int),0);
    cout << "receive data...\n";
    cout << row << "  " << col << endl;
    int * p;
    p = new int[col * row];
    recv(connectfd, p, sizeof(int) * col * row, 0);
    for (i = 0; i < row; i++)
    {
        for(j = 0; j < col; j++)
            cout << p[i * col + j] << "  ";
        cout << endl;
    }
    int max = p[0];
    for (i = 0; i < row; i++){
        for (j=0; j<col; j++)
            if (max < p[i*col+j])
            {max=p[i*col+j];}
    }
    send(connectfd, &max, sizeof(max),0);
    cout << endl;
    delete []p;

    // finish
    close(connectfd);
    close(socketfd);
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).