-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
91 lines (69 loc) · 1.56 KB
/
server.cpp
File metadata and controls
91 lines (69 loc) · 1.56 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
82
83
84
85
86
87
88
89
90
91
// including libraries
#include <iostream>
#include <winsock2.h>
#include <fstream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main()
{
WSADATA WsaDat;
if(WSAStartup(MAKEWORD(2,2),&WsaDat)!=0)
{
std::cout<<"WSA Initialization failed!\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// socket connection
SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(Socket==INVALID_SOCKET)
{
std::cout<<"Socket creation failed.\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// setting the socket
SOCKADDR_IN serverInf;
serverInf.sin_family=AF_INET;
serverInf.sin_addr.s_addr=INADDR_ANY;
serverInf.sin_port=htons(55595);
// bind socket to port
if(bind(Socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
{
std::cout<<"Unable to bind socket!\r\n";
WSACleanup();
system("PAUSE");
return 0;
}
// listen socket
listen(Socket,1);
SOCKET TempSock=SOCKET_ERROR;
while(TempSock==SOCKET_ERROR)
{
std::cout<<"Waiting for incoming connections...\r\n";
TempSock=accept(Socket,NULL,NULL);
}
Socket=TempSock;
std::cout<<"Client connected!\r\n\r\n";
char buffer1[1000];
memset(buffer1,0,999);
// receive data
int inDataLength=recv(Socket,buffer1,1000,0);
// file creation at server end
ofstream myfile ("sample1.txt");
if (myfile.is_open())
{
myfile <<buffer1;
myfile.close();
}
else cout << "Unable to open file";
// Shutdown socket
shutdown(Socket,SD_SEND);
// Close socket entirely
closesocket(Socket);
// Cleanup Winsock
WSACleanup();
system("PAUSE");
return 0;
}