client.C
上传用户:shtangtang
上传日期:2007-01-04
资源大小:167k
文件大小:2k
- #define __THREADS_MAIN
- #include <thread.h>
- extern "C" {
- #include <stddef.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <errno.h>
- #include <fcntl.h>
- #include <sys/mman.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/file.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include <sys/time.h>
- };
- char share[90];
- struct sockaddr_un sock;
- int sock_id;
- size_t size;
- int local_socket(const char *fname)
- {
- if ( (sock_id = socket(PF_LOCAL,SOCK_DGRAM,0)) < 0 )
- return -1;
- sock.sun_family = AF_LOCAL;
- strncpy(sock.sun_path,fname,sizeof(sock.sun_path));
- size = SUN_LEN(&sock);
- if ( bind(sock_id,(struct sockaddr *)&sock,size) < 0 )
- return -1;
- return sock_id;
- }
- int local_recv(const char *msg, int max)
- {
- struct sockaddr_un named_sock;
- size_t size = sizeof(struct sockaddr_un);
- int nbytes;
- nbytes = recvfrom(sock_id,(void *)msg,max,0,(struct sockaddr *)&named_sock,&size);
- cout << "read " << nbytes << " bytes.n";
- return nbytes;
- }
- int local_send(const char *msg)
- {
- int nbytes;
- nbytes = sendto(sock_id,msg,strlen(msg)+1,0,(struct sockaddr *)&sock,size);
- cout << "sent " << nbytes << " bytes.n";
- return nbytes;
- }
- int local_input(int seconds)
- {
- fd_set set;
- struct timeval timeout;
- FD_ZERO(&set);
- FD_SET(sock_id,&set);
- timeout.tv_sec = seconds;
- timeout.tv_usec = 0;
- return select(FD_SETSIZE,&set,NULL,NULL,&timeout);
- }
- class server : public pthread {
- private:
- char *buf;
- public:
- server()
- {
- buf = new char[80];
- unlink("/tmp/client");
- cout << "open socketn";
- if ( local_socket("/tmp/client") == -1 )
- exit(-1);
- cout << "restartn";
- restart();
- }
- ~server() { };
- int thread(void *x)
- {
- suspend();
- cout << "server active" << endl;
- while( true ) {
- cout << "loop" << endl;
- if ( local_input(2) == 1 ) {
- if ( local_recv(buf,80) > 0 )
- cout << "server: " << buf << endl;
- }
- }
- }
- };
- int main(int argc, char **argv)
- {
- server *serv;
- if ( argc == 1 ) {
- serv = new server;
- for(int i=1;i<5;i++) {
- local_send("lock me momma, lock me good...");
- sleep(1);
- }
- cout << "join result #" << serv->join() << endl;
- } else {
- unlink("/tmp/client");
- local_socket("/tmp/client");
- for(int i=1;i<5;i++) {
- local_send("rock a bye, baby...");
- sleep(1);
- }
- }
- }