How can my client send two queries (in two different terminals) to the server at the same time? When i try it, only one works, the other closes socket.
main ()
{
readData ();
int serverFd, clientFd, clientFd2,serverLen, clientLen;
struct sockaddr_un serverAddress;/* Server address */
struct sockaddr_un clientAddress; /* Client address */
struct sockaddr* serverSockAddrPtr; /* Ptr to server address */
struct sockaddr* clientSockAddrPtr; /* Ptr to client address */
/* Ignore death-of-child signals to prevent zombies */
signal (SIGCHLD, SIG_IGN);
serverSockAddrPtr = (struct sockaddr*) &serverAddress;
serverLen = sizeof (serverAddress);
clientSockAddrPtr = (struct sockaddr*) &clientAddress;
clientLen = sizeof (clientAddress);
/* Create a socket, bidirectional, default protocol */
serverFd = socket (AF_LOCAL, SOCK_STREAM, DEFAULT_PROTOCOL);
serverAddress.sun_family = AF_LOCAL; /* Set domain type */
strcpy (serverAddress.sun_path, "countries"); /* Set name */
unlink ("countries"); /* Remove file if it already exists */
bind (serverFd, serverSockAddrPtr, serverLen); /* Create file */
listen (serverFd, 5); /* Maximum pending connection length */
while (1) /* Loop forever */
{
/* Accept a client connection */
clientFd = accept (serverFd, clientSockAddrPtr, &clientLen);
while (fork () == 0) /* Create child to send recipe */
{
int recvquery;
char countrynamereceivedquery[200];
while (recvquery=read(clientFd,countrynamereceivedquery,sizeof(countrynamereceivedq开发者_运维技巧uery)))
{
//print results
}
}
Thats my server program. I run it as a background process and then run client program which can search the textfile stored in an array in server. Right now, when i open two terminals and run the client at teh same time, one client quits program, the other client receives the jus-quit-client's query and searches the server. I did create two sockets but the client just quits in both terminals.
Assuming the server allows more than one connection at a time you can create a different socket and use it for opening another connection to the server.
You use the function socket() to create a TCP socket.
You assign a port number with bind() to the socket.
Using listen() the system allows connections to that port.
Repeat the following:
a. accept() gets a new socket for each client that is connected.
b. With send() and recv() you communicate with the client via that new socket.
c. Finally you close the client connection with function close().
精彩评论