Well you could add more debug code,
Code:
///// client
cout<<"[client]Input your name: "<<flush;
getline(std::cin, input);
cout<<input;
if(n = (send(sd, input.data(), input.size(), 0))<0)
{
perror("[client]Write to server error.\n");
return errno;
}
cout << "Sent a message, wait for reply" << endl;
///// server
while((n=recv(client, buf, sizeof(buf), 0))>0)
{
msg.append(buf, buf+n);
cout << "Current msg=" << msg << endl;
}
Or use a debugger.
Code:
$ g++ -g -o client foo.cpp
$ gdb -q client
Reading symbols from client...done.
(gdb) run 127.0.0.1 7777
Starting program: /home/sc/Documents/client 127.0.0.1 7777
[client]Input your name: yo dude
yo dude
Sent a message, wait for reply
^C
Program received signal SIGINT, Interrupt.
0x00007ffff757d66d in __libc_recv (fd=3, buf=0x7fffffffdbe0, n=500, flags=0)
at ../sysdeps/unix/sysv/linux/x86_64/recv.c:28
28 ../sysdeps/unix/sysv/linux/x86_64/recv.c: No such file or directory.
(gdb) bt
#0 0x00007ffff757d66d in __libc_recv (fd=3, buf=0x7fffffffdbe0, n=500, flags=0)
at ../sysdeps/unix/sysv/linux/x86_64/recv.c:28
#1 0x00000000004015d3 in main (argc=3, argv=0x7fffffffded8) at foo.cpp:69
(gdb) up
#1 0x00000000004015d3 in main (argc=3, argv=0x7fffffffded8) at foo.cpp:69
69 while((n = recv(sd, buf, sizeof(buf), 0))>0)
(gdb)
Code:
$ g++ -g -o server main.cpp
$ gdb -q ./server
Reading symbols from ./server...done.
(gdb) set follow-fork-mode child
(gdb) run
Starting program: /home/sc/Documents/server
[server-15525]Waiting at the port 7777
[server-15525]The client connected: 127.0.0.1:51302
[New process 15533]
[server-15533]Waiting a message...
Current msg=yo dude
^C
Thread 2.1 "server" received signal SIGINT, Interrupt.
[Switching to process 15533]
0x00007ffff757d66d in __libc_recv (fd=4, buf=0x7fffffffd9f0, n=1024, flags=0)
at ../sysdeps/unix/sysv/linux/x86_64/recv.c:28
28 ../sysdeps/unix/sysv/linux/x86_64/recv.c: No such file or directory.
(gdb) bt
#0 0x00007ffff757d66d in __libc_recv (fd=4, buf=0x7fffffffd9f0, n=1024, flags=0)
at ../sysdeps/unix/sysv/linux/x86_64/recv.c:28
#1 0x0000000000401b20 in main () at main.cpp:108
(gdb) up
#1 0x0000000000401b20 in main () at main.cpp:108
108 while((n=recv(client, buf, sizeof(buf), 0))>0)
(gdb)
You can clearly see that the server prints out
Current msg=yo dude
and that the client reaches it's own recv() call to read the response.
The problem (for you) is that the exit condition for the recv() loop on the server is the connection being CLOSED!
What you need to do is send a delimiter (say \n) with each message, so that you can construct a recv/send loop in the server which sends back a message for each line received.
> if(n = (send(sd, input.data(), input.size(), 0))<0)
Watch where you're putting the parentheses here.
You're NOT setting n to be the number of bytes sent, which is then compared with zero.