Good afternoon, all!
I'm in the process of writing a chat program. The server is completed, and if I simply telnet into the server with 2 different windows, 2 people can chat in fluid fashion.
However, when I connect 2 clients, the chat appears in lock-step fashion. (ie. Client 1 types a msg to Client 2, but Client 2 doesn't see the msg until Client2 types a message first.)
Here is a snippet of the code. Any pointers would be great!
And thank you in advance for any assistance!
- Jim
// Open an unbound TCP socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
pdie("Opening stream socket");
// Prepare for connection to server
bzero((char *) &server, sizeof(server));
server.sin_family = AF_INET;
if ((hp = gethostbyname(argv[1])) == NULL)
{
sprintf(buf, "%s: unknown host\n", argv[1]);
die(buf);
}//end preparation
bcopy(hp->h_addr, &server.sin_addr, hp->h_length);
server.sin_port = htons((u_short) SERVER_PORT);
// Establish connection to server
if (connect(sock, (struct sockaddr *) &server, sizeof(server)) <
0)
pdie("Connecting stream socket");
// What socket number am I talking on?
clientLen = sizeof(client);
if (getsockname(sock, (struct sockaddr *) &client, &clientLen))
pdie("Getting socket name");
if (clientLen != sizeof(client))
die("getsockname() overwrote name structure");
printf("Client socket has port %hu\n", ntohs(client.sin_port));
int name = ntohs(client.sin_port);
printf("Now the client name is %d\n\n", name);
gets (msg);
while (msg != "q")
{
/* Write out message. */
if (write(sock, msg, sizeof(msg)) < 0)
pdie("Writing on stream socket");
/* Prepare buffer and read from it. */
bzero(buf, sizeof(buf));
if (read(sock, buf, BUFFER_SIZE) < 0)
pdie("Reading stream message");
printf("User %d says: %s\n", name, buf);
gets(msg);
}
close(sock);
exit(0);
}