BSD Socket Easy Incoming Manual (http:www.fanqiang.com)

xiaoxiao2021-03-06  41

This article comes from: linuxdby.yeah.net Author: Translation: Wilbur Lang (2001-08-21 09:00:00)

Capacity (What is Socket?) Install your new phone (how to listen to?) Dial (How to call Socket) Talk (how to talk to Sockets) hang (end) World language (communication language is very important) Future in your master (Next?) Introducing that after you enter UNIX mysterious world, it will immediately find that more and more things are difficult to understand. For most people, the concept of BSD Socket is one of them. This is a very short tutorial to explain what they are, how do they work and give some simple code to explain how to use them. The class ratio (What is Socket?) Socket is a BSD method for program communication (IPC). This means that the socket is used to interwork information and other processes, just like our calls and other people. It is very appropriate to use the phone to metaphor, we will always describe the concept of the phone. Install your new phone (how to listen?) A person must be able to receive the call from others, first of all, he wants to install a call. Similarly, you must first create Socket to listen to the line. This process contains several steps. First of all, you have to build a new Socket, just like the phone first. The Socket () command completes this job. Because Sockets has several types, you have to indicate what type you want to build. You have to make a choice is the address format of the socket. Like both the phone with audio and pulse, Socket has two most important options that are AF_UNIX and IAF_INET. AF_UNIX identifies Sockets like UNIX path names. This form is useful for IPCs on the same machine. AF_INET uses the four decimal numbers of the four decimal numbers such as 192.9.200.10. In addition to the machine address, port numbers can be utilized to allow multiple AF_INET SOCKETs on each machine. We will focus on the AF_INET method here because he is useful and widely used. Another parameter you must provide is the type of socket. Two important types are SOCK_STREAM and SOCK_DGRAM. SOCK_STREAM indicates that the data is characterized by Socket. Sock_DGRAM indicates that the data will be in the form of a datagrams. We will explain Sock_Stream Sockets, which is very common and easy to use. After building Socket, we will provide the address of the socket listening. Just like you have to answer the phone number. Bind () function to process this matter. SOCK_STREAM Sockets allows the connection request to form a queue. If you are busy with a connection, other connection requests will always wait until the connection is complete. The listen () function is used to set the maximum number of requests (generally 5). Generally do not use the listen () function. The following code shows how to connect to the socket (), bind (), and listen () functions and accept data.

/ * Code to establish a socket; originally from bzs@bu-cs.bu.edu * / int establish (unsigned short portnum) {char myname [MAXHOSTNAME 1]; int s; struct sockaddr_in sa; struct hostent * hp; memset (& SA, 0, SIZEOF (STRUCT SOCKADDR_IN)); / * CLEAR OUR Address * / gethostname (MyName, MaxHostName); / * Who Are We? * / hp = gethostbyname (MyName); / * get outless info * / if (HP == NULL) / * We don't exist!? * / return (-1); sa.sin_family = hp-> h_addrtype; / * this is out address * / sa.sin_port = htons (portnum); / * this is out number * / if ((s = socket, sock_stream, 0)) <0) / * create socket * / return (-1); if (Bind (S, & SA, SIZEOF (Struct SockAddr_in ))) <0) {close (s); return (-1); / * bind address to socket * /} listen (s, 3); / * max # of queued connects * / return (s);} is created After SOCKET, you have to wait for the call to the socket. The accept () function comes to this purpose. Calling accept () Lifting the phone after the phone is ringing. Accept () returns a new Socket connected to the caller. The following code demo is a presentation. / * WAIT for a connection to occur on a socket created with establish () * / int GET_CONNECTION (INT S) {Int T; / * Socket of connection * / if ((t = accept (s, null, null) < 0) / * accept connection if there is one * / return (-1); return (t);} and phones are different, you can also accept calls when you handle previous connections. To this end, it is generally used to handle each connection. The following code demonstrates how to use Establish () and get_connection () to process multiple connections.

#include / * Obligatory Includes * / #include #include #include #include #include #include #include #include #define portnum 5000 / * random port number, we need something * / void fireman (void); void do_something (int); main () {Int S, T; IF ((S = ESTABLISH (portnum)) <0) {/ * plug in the phone * / perror ("eStablish"); exit (1);} SIGNAL Sigchld, Fireman); / * this Eliminates Zombies * / for (;;) {/ * loop for phone calls * / if ((t = get_connection (s)) <0) {/ * get a connection * / if (errno == ENTR) / * Eintr Might Happen on Accept (), * / Continue; / * Try again * / perror ("accept"); / * BAD * / EXIT (1);} switch (fork ()) {/ * Try to handle connection * / case -1: / * bad news. Scream and die * / perror ("fork"); close (s); close (T); exit (1); case 0: / * wE ' Re the child, do something * / close (s); do_something (t); exit (0); default: / * We're the parent so look for * / close (t); / * another connection * / continue;}}} / * as children Die We shop get catch their return} or else we get * zombies, a bad thing. Fireman () catchs falling children. * / void fireman (void) {While (WaitPid (-1 , NULL, WNOHANG> 0);} / * this is the function That Plays with the socket. It will be called * after getting a connection. * / Void do_something (int S) {/ * do your thing with the socket here :: * /} Dial (How to Call Socket) Now you should know how to build Socket to accept call. So how do you call? Like the phone, you have to have a call. With the socket () function to complete this matter, just like the Socket that is listening. After giving the socket address, you can use the connect () function to connect the listen Socket. Here is a code.

int call_socket (char * hostname, unsigned short portnum) {struct sockaddr_in sa; struct hostent * hp; int a, s; if ((hp = gethostbyname (hostname)) == NULL) {/ * do we know the host's * / Errno = ECONNREFUSED; / * Address? * / Return (-1); / * no * /} MemSet (& SA, 0, SIZEOF (SA)); Memcpy ((char *) & sa.sin_addr, hp-> h_addr, HP -> h_length); / * set address * / sa.sin_family = hp-> h_addrtype; sa.sin_port = htons ((u_short) portnum); if ((S = Socket (hp-> h_addrtype, sock_stream, 0)) < 0) / * GET SOCKET * / RETURN (-1); IF (Connect (S, & SA, SIZEOF SA <0) {/ * connect * / close (s); return (-1);} return (s) This function returns a Socket that can flow through data. Talk (how to talk through Sockets), you have established a connection between the two sides to transfer data, now the transfer data. The read () and write () functions are processed. In addition to one of Socket read and write and file reading and writing, and the general file is handled. The difference is that you usually do not get the number of data you want. So you have to loop from the arrival of the data you need. A simple example: read certain data to the cache. INT Read_Data (int S, / * connect socket * / char * buf, / * pointer to the buffer * / int N / * number of character of character {int bcount; / * counts bytes {@ / / * COUNTS BYTES READ * / INT br; / * bytes read this pass * / bcount = 0; br = 0; While (BCOUNT 0) {BCOUNT = Br; / * Increment Byte Counter * / BUF = Br; / * Move Buffer Ptr for Next Read * /} else IF (br) / * signal an error to the caller * / return (-1);} return (bcount);} The same function can also write data, leave our readers. Hanging (end) and you have to close the connection between the Socket by phone and someone. The general close () function is used to turn off the socket connection of each side. If you have closed it, and the other side is written to him, an error code is returned. The Chinese language (the language of communication is very important) Now you can contact between the machine, but be careful what you said. Many machines have their own dialects such as ASCII and EBCDIC. More common problems are byte order issues. Unless you are transferring, you must pay attention to this problem. Fortunately, people have found a solution. A long time ago, what kind of order is more "correct". Now there is a corresponding function to switch now.

Among them, HTONS (), NTOHS (), HTONL () and NTOHL () are available. Convert it first before transmitting a integer data. I = HTONL (i); Write_Data (S, & I, SIZEOF (i)); after reading data, change again. Read_Data (S, & I, SIZEOF (i)); i = ntohl (i); if you have been insisting on this habit, you will be more error more than others. The future is in your master (next step?) Use the things we just discussed, you can write your own communication program. Like all new things, it is best to see what others have done. There are many things about BSD Socket for reference. Please note that there is no error check in the example, which is important in "real" program (http://www.fanqiang.com)

转载请注明原文地址:https://www.9cbs.com/read-54684.html

New Post(0)