-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
117 lines (83 loc) · 2.34 KB
/
Copy pathclient.c
File metadata and controls
117 lines (83 loc) · 2.34 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <glib.h>
#include <gio/gio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
char ip[25], recvBuffer[1000], sendBuffer[1000], command[1000];
void clearBuffers()
{
memset(sendBuffer,'\0',sizeof(sendBuffer));
memset(recvBuffer,'\0',sizeof(recvBuffer));
}
void client_function(int clientPort)
{
printf("Enter IP\n");
//scanf("%s",ip);
strcpy(ip ,"127.0.0.1");
printf("I have entered the client\n");
//creating the socket
GSocket *socket;
GError *error=NULL, *error2=NULL;
socket = g_socket_new (G_SOCKET_FAMILY_IPV4, G_SOCKET_TYPE_STREAM,0, &error);
//checking if the socket is formed
if(socket == NULL)
{
printf("Error in creating the socket.\n");
return;
}
GSocketAddress *address;
address = g_inet_socket_address_new_from_string (ip,clientPort);
//Binding the socket
/* if(!(g_socket_bind (socket,address, FALSE ,&error)))
{
printf("Error in binding socket\n");
return;
}
printf("Socket binding to client successful\n");*/
//Attempting to connect to server
GCancellable *cancellable = g_cancellable_new ();
g_socket_connect (socket,address,cancellable,&error);
if(error!= NULL)
{
printf("Connection failed\n");
return;
}
printf("Connection successful\n");
//Starting the protocol
//Initial greeting
int len;
len= g_socket_receive (socket,recvBuffer,1000,cancellable,&error);
recvBuffer[len]='\0';
printf("%s\n",recvBuffer);
clearBuffers();
//Subsequent interaction
while(1)
{
scanf("%s",command);
//printf("command was:%s\n", command);
strcpy(sendBuffer,command);
//printf("sending: %s\n",sendBuffer );
g_socket_send (socket,sendBuffer,strlen(sendBuffer),cancellable,&error);
clearBuffers();
//printf("Message sent. Awaiting response\n");
g_socket_receive (socket,recvBuffer,1000,cancellable,&error);
printf("S: %s\n",recvBuffer);
clearBuffers();
/*g_socket_receive (socket,recvBuffer,1000,cancellable,&error);
printf("S: %s\n",recvBuffer);
clearBuffers();*/
//Clearing the value of the send and recv buffers at the end of each iteration
memset(sendBuffer,'\0',sizeof(sendBuffer));
memset(recvBuffer,'\0',sizeof(recvBuffer));
}
}
int main()
{
g_type_init();
unsigned int clientPort;
printf("Welcome \nPlease Enter the port on which you want the client: ");
scanf("%d", &clientPort);
client_function(clientPort);
}