Socket socket (SOCKET)
Socket SOCKET:IP address + port port number. In the TCP/IP protocol, it uniquely identifies a process in network traffic.
In the TCP protocol, the two processes that establish the connection each have a socket to identify, then the socketpair of the two sockets uniquely identifies a connection.
The socket itself has the meaning of "socket", so it is used to describe a one-to-a-connection relationship.
The TCP/IP protocol specifies that the network traffic should take a big endian byte order, i.e. (memory) low address high byte (data).
Second,Tcp_socket related
TCP protocol----based on byte stream---sock_stream
IPV4 address format defined in Netinet/in.h, IPv4 address: sockaddr_in struct, including 16-bit port number and 32-bit IP address
H means that host,n indicates that network,l represents a 32-bit long integer and s represents a 16-bit short integer.
650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/80/70/wKiom1dBn4qzcaVWAACcBO7tGTg025.jpg "title=" Sockaddr.jpg "alt=" Wkiom1dbn4qzcavwaaccbo7tgtg025.jpg "/>
#include <sys/types.h>
#include <sys/socket.h>
int socket (int domain, int type, int protocol); Creating sockets
Domain: Protocol af_inet (IPV4), Af_inet6 (IPV6), Af_unix used by the underlying communication
Type: The way the protocol is implemented Sock_stream ordered, reliable, bidirectional, and connection-based byte-stream //protocol: The protocol used by the socket interface. After the first two parameters are set, it can be specified here with 0, indicating the default.
Return value: Descriptor for successful new socket, failed-1
int bind (int sockfd, const struct SOCKADDR *addr,socklen_t Addrlen);//Binding
int listen (int sockfd, int backlog); Listening
SOCKFD: The socket Number (descriptor) already established Sock_stream Sock_dgram
Backlog: Maximum length of the connection request queue
Return value: Success 0, Failure-1
int accept (int sockfd, struct sockaddr *addr, socklen_t *addrlen);//Blocking wait
Return value: The descriptor of the accept socket for a successful nonnegative integer, Failure-1
int connect (int sockfd, const struct SOCKADDR *addr,socklen_t Addrlen);
Return value: Connection/bind succeeded 0, failed-1
#include <unistd.h>
ssize_t Write (int fd, const void *buf, size_t count);
ssize_t Read (int fd, void *buf, size_t count);
Third, the TCP protocol communication process
1, Server: Call socket (), bind (), listen () After completion of initialization, call accept () blocking wait, in the state of the listening port.
Client: After invoking the socket () initialization, call Connect () to emit a SYN segment and block waiting for the server to answer, the server answers a syn-ack segment, the client receives a return from connect (), and answers an ACK segment, which the server receives and returns from accept ().
2, the process of data transmission
After the connection is established, the TCP protocol provides full-duplex communication service, but the general client/server process is initiated by the client, the server passively processes the request, and a question-and-answer method. Therefore, when the server is returned from accept (), the socket is read () immediately, and if no data arrives to block the wait, the client calls write () to send the request to the server, and the server returns from read () to process the client's request. During this time the client calls read () blocking the server's answer, the server calls write () sends the processing results back to the client, calls the read () block again to wait for the next request, the client receives the next request from Read (), and then loops down.
If the client does not have more requests, call Close () to close the connection, just as the write-side closes the pipe, and the server's read () returns 0, so the server knows that the client closed the connection and also called Close () to close the connection. Note that after either party calls Close (), the two transmission directions of the connection are closed and no more data can be sent. If a party calls shutdown () The connection is in a semi-closed state and can still receive data from the other side.
Iv. examples of TCP socket APIs
Tcp_server.cpp
#include <iostream>using namespace std; #include <string.h> #include <stdlib.h> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include < errno.h> #include <netinet/in.h> #include <arpa/inet.h>const int g_backlog=5;void Usage (string _proc) {cout<< "Usage:" <<_proc<< "[Ip][port]" <<ENDL;} Static int startup (const string &ip,const int &port) //server initialization {int sock=socket (af_inet,sock_stream,0);//Create Socket if (sock < 0) {cout<<strerror (errno) << Endl;exit (1);} struct sockaddr_in local;//filling Local Information local.sin_family=af_inet;local.sin_port=htons (port); local.sin_ Addr.s_addr=inet_addr (Ip.c_str ()); if (Bind (sock, (struct sockaddr*) &local,sizeof (local)) < &NBSP;0)//bind {Cout<<strerror (errno) <<endl;exit (2);} if (Listen (Sock,g_backlog) < 0)//Monitor {Cout<<strerror (errno) << Endl;exit (3);} Return sock;} Void *thread_run (Void *arg) {char buf[1024];int sock= (int) arg;while (1) {memset (buf, ' + '), sizeof (BUF)); Ssize_t _size = read (Sock,buf,sizeof (BUF)-1); if (_size > 0)//read success{buf[_size] = ' + ';} Else if (_size == 0)//close connection{cout<< "Client close ..." <<endl ; break;} Else{cout<<strerror (errno) <<endl;} cout<< "client# " <<BUF<<ENDL;} Close (sock); return null;} Int main (int argc,char *argv[]) {if (argc != 3) {usage (argv[0]); exit (1);} String ip = argv[1];int port = atoi (argv[2]); Int listen_sock=startup (IP, Port); struct sockaddr_in client;socklen_t len=sizeof (client); client.sin_family = af_ Inet;client.sin_port = htons (port); Client.sin_addr.s_addr = inet_addr (Ip.c_str ()); while (1) {Int new_sock=accept (Listen_sock, (struct sockaddr*) &client,&len);//Blocking wait if (new_sock < 0) {cout<<strerror (errno) << Endl;continue;} cout<< "Get a connect ..." << "sock: " <<new_sock<< "ip: " <<inet_ Ntoa (CLIENT.SIN_ADDR) << "port: " <<ntohs (Client.sin_port);} #ifdef _v1_char buf[1024];while (1) {Ssize_t _size = read (new_sock,buf,sizeof (BUF)-1); if (_size > 0)//read success{buf[_size] = ';} Else if (_size == 0)//client close {}else{cout<<strerror (errno) <<endl;} cout<< "client# " <<BUF<<ENDL;} #elif _V2_cout<< "V2" <<endl;pid_t id=fork (); if (id < 0) {Cout<<strerror ( errno) <<endl;exit (1);} Else if (id == 0)//child{string _client=inet_ntoa (CLIENT.SIN_ADDR); close (listen_sock); char buf[1024];while (1) {memset (buf, ' n ', sizeof (BUF)); Ssize_t _size = read (New_sock, Buf,sizeof (BUF)-1); if (_size > 0)//read success{buf[_size] = ' + ';} Else if (_size == 0)//client close {cout<<_client<< "Close ..." <<endl; break;} Else{cout<<strerror (errno) <<endl;} cout<<_client<< "# " <<BUF<<ENDL;} Close (New_sock); exit (0);} Else //father{close (New_sock);} #elif _V3_cout<< "V3" <<endl;pthread_t tid;pthread_create (&tid,null,thread_run, (void*) ARGC);p Thread_detach (tid), #elsecout << "Defauult" <<endl; #endifreturn 0;}
//tcp_client.cpp
#include <iostream>using namespace std; #include <string.h> #include <stdlib.h> #include <string> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include < errno.h> #include <netinet/in.h> #include <arpa/inet.h>void usage (string _proc) {cout< <_proc<< "[Remote ip][remote port]" <<ENDL;} Int main (int argc,char *argv[]) //tcp_client.cpp{if (argc != 3) {usage (argv[0]); Exit (1);} String r_ip = argv[1];int r_port = atoi (argv[2]);int sock = Socket (af_inet,sock_stream,0), if (sock < 0) {cout<<strerror (errno) <<endl;exit (1);} Struct sockaddr_in remote;remote.sin_family = af_inet;remote.sin_port = htons (r_ Port); Remote.sin_addr.s_addr = inet_addr (R_ip.c_str ()); Int ret = connect (sock, (struct sockaddr*) &remote,sizeof (remote)); if (RET&NBSP;<&Nbsp;0) {cout<<strerror (errno) <<endl;} String msg;while (1) {cout<< "please enter: "; Cin>>msg;write (Sock,msg.c_str (), msg.size ());} return 0;}
Makefile
. PHONY:allall:tcp_server tcp_clienttcp_server:tcp_server.cppg++-o [email protected] $^-lpthread-d_v3_tcp_client:tcp _client.cppg++-o [email protected] $^. Phony:cleanclean:rm-f Tcp_server tcp_client
This article is from the "Flower Open Shore" blog, please be sure to keep this source http://zxtong.blog.51cto.com/10697148/1775963
Socket Programming----TCP protocol