-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_resource.cpp
More file actions
81 lines (71 loc) · 1.99 KB
/
Copy pathserver_resource.cpp
File metadata and controls
81 lines (71 loc) · 1.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* Sockets-server -
* Simple server program to demonstrate sockets usage
* CSS 503
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sys/uio.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
const int BUFFSIZE = 1500;
const int NUM_CONNECTIONS = 5;
int main(int argc, char *argv[])
{
int serverPort;
char *serverName;
char databuf[BUFFSIZE];
bzero(databuf, BUFFSIZE);
/*
* Build address
*/
int port = 12345;
sockaddr_in acceptSocketAddress;
bzero((char *)&acceptSocketAddress, sizeof(acceptSocketAddress));
acceptSocketAddress.sin_family = AF_INET;
acceptSocketAddress.sin_addr.s_addr = htonl(INADDR_ANY);
acceptSocketAddress.sin_port = htons(port);
/*
* Open socket and bind
*/
int serverSD = socket(AF_INET, SOCK_STREAM, 0);
const int on = 1;
setsockopt(serverSD, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(int));
cout << "Socket #: " << serverSD << endl;
int rc = bind(serverSD, (sockaddr *)&acceptSocketAddress, sizeof(acceptSocketAddress));
if (rc < 0)
{
cerr << "Bind Failed" << endl;
}
/*
* listen and accept
*/
listen(serverSD, NUM_CONNECTIONS); //setting number of pending connections
sockaddr_in newSockAddr;
socklen_t newSockAddrSize = sizeof(newSockAddr);
int newSD = accept(serverSD, (sockaddr *) &newSockAddr, &newSockAddrSize);
cout << "Accepted Socket #: " << newSD <<endl;
/*
* read from the socket
*/
int bytesRead = read(newSD, databuf, BUFFSIZE);
cout << "Bytes Read: " << bytesRead << endl;
cout << databuf[0] << endl;
/*
* write to socker
*/
databuf[13] = 'R';
int bytesWritten = write(newSD, databuf, BUFFSIZE);
cout << "Bytes Written: " << bytesWritten << endl;
close(newSD);
close(serverSD);
return 0;
}