I am trying to implement a simple chat program in linux using bsd sockets. Right now I am just trying to send and receive one message to the server from a client. Whenever I run the code, recv returns -1 and the errno code is 22.
Server code -
struct sockaddr name;
char buf[80];
int main(int agrc, char** argv) {
int sock, new_sd; //sock is this socket, new_sd is connection socket
int adrlen, cnt;
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/servsock");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
cout<<"\nserver socket failure "<<errno;
cout<<"\nServer: ";
exit(1);
}
unlink("/tmp/servsock");
if(bind (sock, &name, adrlen) < 0)
cout<<"\nBind failure "<<errno;
if(listen(sock, 5) < 0)
cout<<"\nlisten error "<<errno;
while(1) {
if( new_sd = accept(sock, &name, (socklen_t*)&adrlen) < 0) {
cout<<"\nserver accept failure "<<errno;
exit(1);
}
char* buf = new char[14];
if(recv(sock, buf, 14, 0) < 0) {
cout<<"\nError receiving data "<<errno;
exit(1);
}
} //end while
return 0;
}
Client code -
struct sockaddr name;
int main(int agrc, char** argv) {
int sock, new_sd, adrlen, cnt;
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
cout<<"\nserver socket failure "<<errno;
cout<<"\nServer: ";
exit(1);
}
//stuff for server socket
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "/tmp/servsock");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
if(connect(sock, &name, adrlen) < 0) {
cout<<"\nclient connection failure "<<errno;
exit(1);
}
cout<<"\nSuccessful connection from client 1";
std::string buf = "\nClient 1 Here";
if(send(sock, buf.c_str(), strlen(buf.c_str()), 0) < 0) {
cout<<"\nError sending data from client 1 "<<errno;
exit(1);
}
cout<<"\nExiting normally";
return 0;
}
Even though I get the error on the server side, I do not get the error message on the client side - it just exits normally.
According to - http://www.workers.com.br/manuais/53/html/tcp53/mu/mu-7.htm the errno 22 error message just means "Invalid argument". But I don't know how exactly to interpret that...if an argument was invalid why would it even compile?
If anyone can point out what I'm doing wrong here I would be very grateful. And any other small notes you feel like pointing out would be welcomed. Thanks for any help.
Aside from all other problems in your code, you are trying to read on the wrong file descriptor - it should be new_sd, not sock, which is a server socket and can only accept() new connections.
Edit 0:
Big boo-boo:
if( new_sd = accept(sock, &name, (socklen_t*)&adrlen) < 0) { ...
This is equivalent to:
if( new_sd = (accept(sock, &name, (socklen_t*)&adrlen) < 0)) {
So new_sd gets totally wrong value. General wisdom is not to put assignments into conditionals. Consider compiling with high warning levels, at least -Wall -pedantic.
One thing that looks wrong in your code is that you're recving on sock when you should be recving from new_fd. Not sure why that would give EINVAL though.
(EINVAL errors are (usually) not detectable at compile time. File descriptors are plain ints. The compiler cannot know which ints are valid file descriptors at runtime, or if a particular combination of flags is valid for the sockets you're using for instance.)
In the'recv()' call (in the server), the 'flags' parameter can't be 0:
recv(sock, buf, 14, 0)
Try something like:
recv(sock, buf, 14, MSG_WAITALL)
See the 'man' page for the whole list of options for 'flags' parameter. One must be judicious here on how the message is to be received.
The reason why the client doesn't get the error message (INVALID ARG) is because it doesn't do any recv's ... only the server is doing receive's.
Related
I'm trying to get comfortable with socket programming. I've written a client/server game, and am seeing some strange results.
Below is the code for the client portion:
while(1){
char response[100];
memset(&buf[0], 0, sizeof(buf));
//buf[numbytes] = '\0';
socklen_t addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, buf, MAXDATASIZE-1, 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recv");
exit(1);
}
if (strcmp(buf, "exit 99") == 0){
close(sockfd);
return 0;
}
printf("%s\n",buf);
std::cin >> response;
struct msgstruct message;
message.send_data = response;
message.length = strlen(message.send_data);
int n = sendto(sockfd, response, strlen(response), 0, p->ai_addr, p->ai_addrlen);
}
This communicates through the "server", via the following code snippet:
int StartMasterMind(int client, sockaddr_storage addr_in)
{
struct sockaddr_storage their_addr = addr_in;
socklen_t addr_len;
char buf[MAXDATASIZE];
buf[MAXDATASIZE] = '\0';
sendMsg(client, "Welcome to ... M-A-S-T-E-R-M-I-N-D.\nThe game has begun.\n");
// [..] redacted for clarity
for (int i = 0; i < 8; ++i) {
sendMsg(client, "Please enter your guess: ");
addr_len = sizeof their_addr;
recv(client, buf, MAXDATASIZE-1, 0/*, (struct sockaddr *)&their_addr, &addr_len*/);
current_try = GetInputAsColorMap(buf);
// [..] redacted for clarity -- several for() loops below here
}
//basic message structure
struct msgstruct {
int length;
char* send_data;
};
//basic method for sending messages
int sendMsg(int client, char* theMsg)
{
msgstruct message;
message.send_data = theMsg;
message.length = strlen(message.send_data);
return (send(client, message.send_data, message.length, 0));
}
So, if I connect via local host: ./client localhost <port>, then everything appears to be ok:
c#ub1:~/Documents/dev$ ./client localhost 9990
client: connecting to 127.0.0.1
Welcome to ... M-A-S-T-E-R-M-I-N-D.
The game has begun.
Please enter your guess:
However, when connecting over the network from another VM, I consistently get:
c#ub1:~/Documents/dev$ ./client 192.168.1.111 9990
client: connecting to 192.168.1.111
Welcome to ... M-A-S-T-E-R-M-I-N-D.
The game has begun.
Notice the missing Please enter your guess: - I'm a bit at a loss for what to do here. I can't figure out why/when/where this data is getting dropped. Because of this, I'm a little afraid to continue, because I just assume somewhere I have a buffer that's going to overflow and wreck everything.
You're making all the usual mistakes. You're assuming that one send equals one receive. You're not making use of the read count returned by recv() when using he receive buffer. You're assuming that TCP is a messaging protocol. It's a byte-stream protocol.
I am trying to make a program that uses HTTP in winsock, but I have run into a problem where the recv function just hangs there.
int connect()
{
WSADATA t_wsa; //WSADATA structure
WORD wVers = 0x0202; //version number
int iError; //error number
wVers = MAKEWORD(2, 2); // Set the version number to 2.2
iError = WSAStartup(wVers, &t_wsa); // Start the WSADATA
if(iError != NO_ERROR || iError == 1)
{
printf("Error at WSAStartup()\n");
WSACleanup();
system("PAUSE");
return 1;
}
/* Correct version? */
if(LOBYTE(t_wsa.wVersion) != 2 || HIBYTE(t_wsa.wVersion) != 2)
{
printf("Incorrect version\n");
WSACleanup();
system("PAUSE");
return 1;
}
SOCKET sClient;
sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sClient == INVALID_SOCKET || iError == 1)
{
printf("Invalid Socket!\n");
WSACleanup();
system("PAUSE");
return 1;
}
SOCKADDR_IN sinClient;
memset(&sinClient, 0, sizeof(sinClient));
char cIP[50];
strcpy_s(cIP, "98.139.183.24");
sinClient.sin_family = AF_INET;
sinClient.sin_addr.s_addr = inet_addr(cIP); // Where to start server
sinClient.sin_port = htons(80); //Port
if(connect(sClient, (LPSOCKADDR)&sinClient, sizeof(sinClient)) == SOCKET_ERROR)
{
/* failed at starting server */
printf("Could not connect ot the server!\n");
WSACleanup();
system("PAUSE");
return 1;
}
// Now we can send/recv data!
printf("YOU ARE CONNECTED!\r\n");
string buffer;
buffer += "GET / HTTP/1.1\r\n";
buffer += "Host: http://www.yahoo.com/\r\n";
buffer += "Connection: close\r\n\r\n";
const char *cha = buffer.c_str();
int sent;
int response;
sent = send(sClient, cha, sizeof(cha) - 1, 0);
char recvbuf[50000];
response = recv(sClient, recvbuf, 50000, 0);
recvbuf[response] = '\0';
printf("\nReceived data = %s", recvbuf);
WSACleanup();
return(0);
}
"sent" will get printed after the send function, but nothing after recv gets printed.
What am I missing here?
A possible cause is that the send() is not sending the data intended:
sent = send(sClient, cha, sizeof(cha) - 1, 0);
the sizeof(cha) - 1 is actually sizeof(char*) - 1, not the actual length of the data: use buffer.length() instead.
Note that you can construct the std::string with the string literal in a single statement instead of constructing it via several concatentations. However, as the std::string is being used to obtain a const char* only there is no reason for using std::string at all:
const char* buffer = "GET / HTTP/1.1\r\n"
"Host: http://www.yahoo.com/\r\n"
"Connection: close\r\n\r\n";
sent = send(sClient, buffer, strlen(buffer), 0);
Check the return value of send() and recv() to determine success or failure, particularly recv() as the result is being used to index an array. On failure, recv() returns SOCKET_ERROR which (I think) is -1.
Handling HTTP responses correctly requires significant effort. The receiving code needs to examine the returned HTTP headers to determine how to handle the response content. For example, a HTTP response may be chunked or not. Libraries exist for managing HTTP requests, one is cpp-netlib (which was announced on isocpp.org circa February 2013).
I'm writing client-server application. Until now everything was OK, client sent a request, server recieved it, parse it. But now I want to send back an answer, so I copied those two functions, I put write() from client to server and read() from server to client. And when I run the program now everything blocks, server waits, client waits too. When I ctrl+c client, server unblocks and parse the right request and waits for another. What could be wrong, please?
Part of code from client:
params.port = atoi(params.pvalue.c_str());
hostent *host;
sockaddr_in socketHelper;
int clientSocket;
char buf[BUFFER_LEN];
int size;
string data;
string recieved;
// gets info about server
host = gethostbyname(params.hvalue.c_str());
if(host == NULL) {
printErr(ERR_HOSTNAME);
return ERR_HOSTNAME;
}
// makes a socket
if((clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
printErr(ERR_SOCKET);
return ERR_SOCKET;
}
socketHelper.sin_family = AF_INET;
socketHelper.sin_port = htons(params.port);
memcpy(&(socketHelper.sin_addr), host->h_addr, host->h_length);
// connects the socket
if(connect(clientSocket, (sockaddr *)&socketHelper, sizeof(socketHelper)) == -1) {
printErr(ERR_CONNECTION);
return ERR_CONNECTION;
}
// sends data
if((size = write(clientSocket, request.c_str(), request.length())) == -1) {
printErr(ERR_SEND);
return ERR_SEND;
}
// recieves data
while ((size = read(clientSocket, buf, BUFFER_LEN)) != 0) {
recieved.erase();
recieved.append(buf, size);
data = data + recieved;
}
// closes a connection
close(clientSocket);
And part of code from server:
while(1) {
int clientSocket = accept(GodParticle, (struct sockaddr*) &GodAddr, &clientSocketSize);
if(clientSocket == -1) {
printErr(ERR_ACCEPT);
return ERR_ACCEPT;
}
if((pid = fork()) == 0) {
while ((size = read(clientSocket, buf, BUFFER_LEN)) != 0) {
recieved.erase();
recieved.append(buf, size);
request = request + recieved;
}
parserInput(request);
getData();
parserOutput();
if((size = write(clientSocket, sendback.c_str(), sendback.length())) == -1) {
printErr(ERR_SEND);
return ERR_SEND;
}
close(clientSocket);
exit(ERR_OK);
}
}
Ok, let me answer in this way.
recv() is blocking your program by default until it receive some message from server.
And the reason why recv() does not blocks your server program is because you used fork() to create a child process.
So you have to use some other method to avoid this block(maybe like using select or some other things).
I've been trying to send a packet from a client to a server via sockets. With the help of some of the tips I have made quite bit of progress in my code. However, the server only receives eight bytes from the client and prints them on the console whereas at my client side, It seems that it has sent everything.
Now I am not sure whether the problem is at the sending side or the receiving side. My hunch is that something is wrong at my client side. Could someone please help in verifying my assumption?
Client code:
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
data_struct client_data;
struct packet
{
long int srcID;
long int destID;
int pver;
int profiles;
int length;
long int data;
};
if (argc < 3) {
fprintf(stderr,"usage: %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]); //Convert ASCII to integer
sockfd = socket(AF_INET, SOCK_STREAM, 0); // socket file descriptor
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket\n");
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR DETECTED !!!, no such server found \n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr)); //clear the memory for server address
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
serv_addr.sin_port = htons(portno);
printf("Client 1 trying to connect with server host %s on port %d\n", argv[1], portno);
if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR in connection");
printf("SUCCESS !!! Connection established \n");
char buffer[256];
struct packet *pkt = (struct packet *) buffer;
char *payload = buffer + sizeof(struct packet);
long double packet_size;
printf("Started Creating packet\n");
pkt->srcID = 01;
pkt->destID = 02;
pkt->pver = 03;
pkt->profiles = 01;
pkt->length = 16;
pkt->data = 1; 2; 3; 4; 5; 6; 7; 8;
{
if (send(sockfd,pkt,sizeof(packet_size),0) <0)
printf ("error\n");
else
printf ("packet send done");
}
return 0;
}
Server code:
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
int n;
char wish;
long int SrcID;
long int DestID;
int Pver;
int Profiles;
long int Data;
int Length;
char bytes_to_receive;
int received_bytes;
struct packet
{
long int srcID;
long int destID;
int pver;
int profiles;
int length;
long int data;
};
if (argc < 2) {
fprintf(stderr,"usage: %s port_number1",argv[0]);
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR DETECTED !!! Problem in opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR DETECTED !!! There was a problem in binding");
listen(sockfd, 10);
clilen = sizeof(cli_addr);
printf("Server listening on port number %d...\n", serv_addr.sin_port);
newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR DETECTED !!! the connection request was not accepted");
char buffer[256];
struct packet *pkt = (struct packet *) buffer;
char *payload = buffer + sizeof(struct packet);
long double packet_size;
bytes_to_receive = sizeof(packet_size);
received_bytes = 0;
int rc =0;
while ((rc = recv(newsockfd,pkt,sizeof(packet_size),0)) > 0)
{
received_bytes+=rc;
SrcID = pkt->srcID;
DestID = pkt->destID;
Pver = pkt->pver ;
Profiles = pkt->profiles;
Length = pkt->length;
Data = pkt->data;
printf("Data Received from Client_1 are :\n");
printf("Source ID: %ld\n", SrcID);
printf("Destination ID: %ld\n", DestID);
printf("profile Version: %d\n", Pver);
printf("No of Profiles: %d\n", Profiles);
printf("Length: %d\n", Length);
printf("data : %ld\n", Data);
}
if (rc == 0)
{
printf("Connection closed by Server\n");
printf("Bytes received: %d\n",received_bytes);
}
if (rc == -1)
{
perror("recv");
}
{
if (close(newsockfd) == -1) {
error("Error closing connection with client 1");
}
printf("Connection with client 1 has been closed\n");
}
return 0;
}
The output that I see on the client's console is:
Client Side: Client 1 trying to connect with server host 130.191.166.230 on port 1234
SUCCESS !!! Connection established
Started Creating packet
packet send done
and on the server's console I see:
Server Side: Data Received from Client_1 are :
Source ID: 1
Destination ID: 2
profile Version: 0
No of Profiles: 1074462536
Length: 0
data : 0
Connection closed by Server
Bytes received: 8
Connection with client 1 has been closed
First of all
recv(newsockfd,pkt,sizeof(packet_size),0)) /* What is packet_size ? */
recv(newsockfd,pkt,sizeof(struct packet),0)) /* You probably mean this. */
That might solve your problems, but there are a few issues with the way you are using TCP sockets.
But at my client side, it prints that it has sent everything
Where ? I don't see you actually checking the number of bytes sent. send(2) can return after sending less that you asked it to.
It shows me that only 8 bytes were sent by Client and prints them out.
TCP is a stream-oriented protocol. You send bytes and they arrive, in the same order. So when you recv(2) something, you might get less (or more than you wrote). So, the following can be true:
client:
send 100 bytes
send 400 bytes
server:
recv 50 bytes
recv 150 bytes
recv 250 bytes
recv 50 bytes
The number of send and recv calls need not be identical when using TCP.
When you call send the function returns the number of bytes actually sent and this number can be less than the number of bytes you wanted to send. So every time you want to send something there must be a loop like the following
bool sendBuffer(SOCKET s, unsigned char *buf, int size)
{
while (size > 0)
{
int sz = send(s, buf, size,0);
if (sz < 0) return false; // Failure
size -= sz; // Decrement number of bytes to send
buf += sz; // Advance read pointer
}
return true; // All buffer has been sent
}
and a similar loop must be done when receiving (in other words recv can return less bytes than what you are asking for).
If you don't make these loops the risk is that everything apparently will work anyway (until the size of an ethernet packet) when you work on your local machine or even over a LAN, but things will not work when working across the internet.
Note also that as other answers pointed out you asked to send sizeof(packet_size) i.e. the number of bytes required to store that variable, not the size of the structure.
There is an informal rule that nobody is allowed to write any software that uses TCP until they memorize this sentence and can fully explain what it means: "TCP is a byte-stream protocol that does not preserve application message boundaries."
What that means is that TCP only ensures that you get out the same bytes you put in and in the same order. It does not "glue" the bytes together in any way.
Before you write any code that uses TCP, you should either use a protocol that is already designed (such as IMAP or HTTP) or design one yourself. If you design one yourself, you should write out a protocol specification. It should specifically define what a protocol-level message will consist of at the byte level. It should specifically state how the receiver finds the ends of messages, and so on.
This may seem a little silly for simple applications, but trust me, it will pay off massively. Otherwise, it's almost impossible to figure out why things aren't work because if the server and client don't quite get along, there's no arbiter to say what's right.
I don't specialise in socket programming but there are a few things I've noticed. As far as I'm aware, I don't think you can send structs over sockets that easily. You may wish to consider a different method.
NB, when using send/recv you're also determing the sizeof packet_size, and not the sizeof the struct.
Googling brought up this about sending structs over sockets: http://ubuntuforums.org/showthread.php?t=613906
I am trying to use non-blocking TCP sockets. The problem is that they are still blocking. The code is below -
server code -
struct sockaddr name;
char buf[80];
void set_nonblock(int socket) {
int flags;
flags = fcntl(socket,F_GETFL,0);
assert(flags != -1);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
}
int main(int agrc, char** argv) {
int sock, new_sd, adrlen; //sock is this socket, new_sd is connection socket
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "127.0.0.1");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
//make socket
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
printf("\nBind error %m", errno);
exit(1);
}
//unlink and bind
unlink("127.0.0.1");
if(bind (sock, &name, adrlen) < 0)
printf("\nBind error %m", errno);
//listen
if(listen(sock, 5) < 0)
printf("\nListen error %m", errno);
//accept
new_sd = accept(sock, &name, (socklen_t*)&adrlen);
if( new_sd < 0) {
cout<<"\nserver accept failure "<<errno;
exit(1);
}
//set nonblock
set_nonblock(new_sd);
char* in = new char[80];
std::string out = "Got it";
int numSent;
int numRead;
while( !(in[0] == 'q' && in[1] == 'u' && in[2] == 'i' && in[3] == 't') ) {
//clear in buffer
for(int i=0;i<80;i++)
in[i] = ' ';
cin>>out;
cin.get();
//if we typed something, send it
if(strlen(out.c_str()) > 0) {
numSent = send(new_sd, out.c_str(), strlen(out.c_str()), 0);
cout<<"\n"<<numSent<<" bytes sent";
}
numRead = recv(new_sd, in, 80, 0);
if(numRead > 0)
cout<<"\nData read from client - "<<in;
} //end while
cout<<"\nExiting normally\n";
return 0;
}
client code -
struct sockaddr name;
void set_nonblock(int socket) {
int flags;
flags = fcntl(socket,F_GETFL,0);
assert(flags != -1);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
}
int main(int agrc, char** argv) {
int sock, new_sd, adrlen;
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
printf("\nserver socket failure %m", errno);
exit(1);
}
//stuff for server socket
name.sa_family = AF_UNIX;
strcpy(name.sa_data, "127.0.0.1");
adrlen = strlen(name.sa_data) + sizeof(name.sa_family);
if(connect(sock, &name, adrlen) < 0) {
printf("\nclient connection failure %m", errno);
exit(1);
}
cout<<"\nSuccessful connection\n";
//set nonblock
set_nonblock(sock);
std::string out;
char* in = new char[80];
int numRead;
int numSent;
while(out.compare("quit")) {
//clear in
for(int i=0;i<80;i++)
in[i] = '\0';
numRead = recv(sock, in, 80, 0);
if(numRead > 0)
cout<<"\nData read from server - "<<in;
cout<<"\n";
out.clear();
cin>>out;
cin.get();
//if we typed something, send it
if(strlen(out.c_str())) {
numSent = send(sock, out.c_str(), strlen(out.c_str()), 0);
cout<<"\n"<<numSent<<" bytes sent";
}
} //end while
cout<<"\nExiting normally\n";
return 0;
}
Whenever I run it, the server still waits for me to send something before it will read and output what the client has sent. I want either the server or client to be able to send the message as soon as I type it, and have the other read and output the message at that time. I thought non-blocking sockets was the answer, but maybe I am just doing something wrong?
Also, I was using a file instead of my 127.0.0.1 address as the sockaddr's data. If that is not how it should be properly used, feel free to say so (it worked how it worked previously with a file so I just kept it like that).
Any help is appreciated.
General approach for a TCP server where you want to handle many connections at the same time:
make listening socket non-blocking
add it to select(2) or poll(2) read event set
enter select(2)/poll(2) loop
on wakeup check if it's the listening socket, then
accept(2)
check for failure (the client might've dropped the connection attempt by now)
make newly created client socket non-blocking, add it to the polling event set
else, if it's one of the client sockets
consume input, process it
watch out for EAGAIN error code - it's not really an error, but indication that there's no input now
if read zero bytes - client closed connection, close(2) client socket, remove it from event set
re-init event set (omitting this is a common error with select(2))
repeat the loop
Client side is a little simpler since you only have one socket. Advanced applications like web browsers that handle many connections often do non-blocking connect(2) though.
Whenever I run it, the server still waits for me to send something before it will read and output what the client has sent.
Well, that is how you wrote it. You block on IO from stdin, and then and only then do you send/receive.
cin>>out;
cin.get();
Also, you are using a local socket (AF_UNIX) which creates a special file in your filesystem for interprocess communication - this is a different mechanism than IP, and is definitely not TCP as you indicate in your question. I suppose you could name the file 127.0.0.1, but that really doesn't make sense and implies confusion on your part, because that is an IP loopback address. You'll want to use AF_INET for IP.
For an excellent starter guide on unix networking, I'd recommend http://beej.us/guide/bgnet/
If you want the display of messages received to be independant of your cin statements, either fork() off a seperate process to handle your network IO, or use a separate thread.
You might be interested in select(). In my opinion non-blocking sockets are usually a hack, and proper usage of select() or poll() is generally much better design and more flexible (and more portable). try
man select_tut
for more information.
I think you have to set non-block sooner (ie get the socket then set it non block)
also check that the fcntl to set it actually worked
If you want non-blocking i/o, you want to use select. You can set it with stdin as one of the sockets it is listening on, along with the client sockets (just add file descriptor 1, which is stdin, to the fd_set).
http://beej.us/guide/bgnet/output/html/multipage/advanced.html
I would recommend reading through what beej has to say about select. It looks a little intimidating but is really useful and simple to use if you take a little time to wrap your head around it.