When I run this program, everything works as expected. It starts up and connects to a server and gets all the stuff the server is supposed to send. However, when I try to type something, it works, but then it won't listen to any more input and I don't think it recieves any more. I have no idea why.
Code:#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#define SOCKET_ERROR -1
#define BUFFER_SIZE 100
#define HOST_NAME_SIZE 255
int main(int argc, char* argv[])
{
int hSocket; /* handle to socket */
struct hostent* pHostInfo; /* holds info about a machine */
struct sockaddr_in Address; /* Internet socket address stuct */
long nHostAddress;
char pBuffer[BUFFER_SIZE];
unsigned nReadAmount;
char strHostName[HOST_NAME_SIZE];
int nHostPort;
char buf[1024];
int n;
if(argc < 3)
{
printf("\nUsage: client host-name host-port\n");
return 0;
}
else
{
strcpy(strHostName,argv[1]);
nHostPort=atoi(argv[2]);
}
/* make a socket */
hSocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(hSocket == SOCKET_ERROR)
{
printf("\nCould not make a socket\n");
return 0;
}
/* get IP address from name */
pHostInfo=gethostbyname(strHostName);
/* copy address into long */
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);
/* fill address struct */
Address.sin_addr.s_addr=nHostAddress;
Address.sin_port=htons(nHostPort);
Address.sin_family=AF_INET;
printf("Connecting to %s on port %d\n",strHostName,nHostPort);
/* connect to host */
if(connect(hSocket,(struct sockaddr*)&Address,sizeof(Address))
== SOCKET_ERROR)
{
printf("\nCould not connect to host\n");
return 0;
}
/* read from socket into buffer
** number returned by read() and write() is the number of bytes
** read or written, with -1 being that an error occured */
printf("Type a ~ to exit\n");
printf("Enter to continue\n");
while(1)
{
gets(buf);
if(buf[0] == '~')
break;
n = strlen(buf);
buf[n] = '\n';
buf[n+1] = 0;
write(hSocket,buf, strlen(buf));
nReadAmount = 1;
while(nReadAmount > 0)
{
nReadAmount=read(hSocket,pBuffer,BUFFER_SIZE);
pBuffer[nReadAmount] = '\0';
printf("%s", pBuffer);
}
printf("\n>");
}
/* write what we received back to the server */
printf("\nClosing socket\n");
/* close socket */
if(close(hSocket) == SOCKET_ERROR)
{
printf("\nCould not close socket\n");
return 0;
}
}