Chat server: Difference between revisions

m
→‎{{header|C}}: mixing space and tabulation in indentation is always a bad idea!
(Add C example.)
m (→‎{{header|C}}: mixing space and tabulation in indentation is always a bad idea!)
Line 99:
A glitch occurs if a connection is made using the Telnet protocol - user names are preceded by garbled text.
 
<lang c>#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
Line 257 ⟶ 256:
int ChatLoop()
{
int i,j;
FD_ZERO(&status);
 
FD_SET(tsocket, &status);
FD_SET(0, &status);
 
while(1)
{
{
current=status;
if (select(FD_SETSIZE, &current, NULL, NULL, NULL)==-1)
{
{
perror("Select");
return 0;
}
}
for (i=0; i<FD_SETSIZE; ++i)
{
{
if (FD_ISSET(i, &current))
{
{
if (i==tsocket)
{
{
struct sockaddr_in cliinfo;
socklen_t addrlen = sizeof(cliinfo);
int handle;
handle=accept(tsocket, &cliinfo, &addrlen);
if (handle==-1)
{
{
perror ("Couldn't accept connection");
} else if (handle>FD_SETSIZE)
{
printf ("Unable to accept new connection.\n");
Line 298 ⟶ 297:
ntohs(cliinfo.sin_port));
FD_SET(handle, &status);
 
AddConnection(handle);
}
}
}
} /* Read data, relay to others. */
else
else
{
{
char buf[512];
int b;
 
b=read(i, buf, 500);
if (b<=0)
{
{
CloseConnection(i);
}
}
else
else
{
{
ClientText(i, buf, b);
}
}
}
}
}
}
}
}
} /* While 1 */
}
 
int main (int argc, char*argv[])
{
tsocket = socket(PF_INET, SOCK_STREAM, 0);
 
tsockinfo.sin_family=AF_INET;
tsockinfo.sin_port=htons(7070);
if (argc>1)
{
{
tsockinfo.sin_port = htons(atoi(argv[1]));
}
}
tsockinfo.sin_addr.s_addr = htonl(INADDR_ANY);
printf ("Socket %d on port %hu\n", tsocket, ntohs(tsockinfo.sin_port));
 
if (bind (tsocket, &tsockinfo, sizeof(tsockinfo))==-1)
{
{
perror("Couldn't bind socket");
return -1;
}
}
 
if (listen(tsocket, 10)==-1)
{
{
perror("Couldn't listen to port");
}
}
 
ChatLoop();
 
return 0;
 
}</lang>
return 0;
}
</lang>
 
=={{header|CoffeeScript}}==