To understand socket First, get familiar with TCP/IP Protocol family , TCP/IP(Transmission Control Protocol/Internet Protocol) Transmission control protocol / Internet Protocol , Defines how hosts connect to the Internet and how data is transferred between them ,

Literally TCP/IP yes TCP and IP General term of agreement , But actually TCP/IP Protocol refers to the Internet as a whole TCP/IP Protocol family . differ ISO The seven layers of the model ,TCP/IP The protocol reference model takes all TCP/IP The series of protocols are grouped into four abstraction layers

application layer :TFTP,HTTP,SNMP,FTP,SMTP,DNS,Telnet wait

Transport layer :TCP,UDP

The network layer :IP,ICMP,OSPF,EIGRP,IGMP

Data link layer :SLIP,CSLIP,PPP,MTU

Each abstraction layer is built on the services provided by the lower layer , And provide services for the higher level , It looks like this


It is estimated that all the students who are interested in opening this article have a certain understanding of it , Plus, I know little about it , So I won't explain it in detail , Interested students can search for information on the Internet


Baidu Encyclopedia

stay TCP/IP In the protocol, two Internet hosts are connected through two routers and corresponding layers . Applications on each host perform read operations to each other through some data channels


We know that if two processes need to communicate, the most basic premise is that one process can be uniquely identified , We can use... In local process communication PID To uniquely identify a process , but PID It's only in the local area , Two processes in the network PID The odds of conflict are high , At this time, we need to find another way , We know IP Layer of ip The address can uniquely identify the host , and TCP Layer protocol and port number can uniquely identify a process of the host , So we can use ip Address + agreement + The port number uniquely identifies a process in the network .

After being able to uniquely identify the processes in the network , They can use socket We're communicating , What is? socket Well ? We often put socket Socket ,socket It's an abstraction layer between the application layer and the transport layer , It is the TCP/IP Layer complex operations are abstracted into several simple interfaces to supply layer calls to realize process communication in the network .

socket Come of UNIX, stay Unix Everything is under the thought of document philosophy ,socket It's a kind of " open — read / Write — close " The realization of pattern , The server and the client each maintain one " file ", After the connection is established and opened , You can write content to your own file for the other party to read or read the other party's content , Close file at the end of communication .

socket Communication process

socket yes " open — read / Write — close " The realization of pattern , To use the TCP Protocol communication socket For example , The interaction process is like this

The server depends on the address type (ipv4,ipv6)、socket type 、 Protocol creation socket

The server is socket binding ip Address and port number

The server socket Listen for port number request , Ready to receive connections from clients at any time , At this point, the server socket It's not opened

Client creation socket

Client open socket, According to server ip The address and port number are trying to connect to the server socket

The server socket Received client socket request , Passive on , Start receiving client requests , Until the client returns the connection information . Now socket Get into Blocking state , Obstruction means accept() Method does not return until the client returns the connection information , Start receiving next client link request

Client connection successful , Send connection status information to the server

The server accept Method returns , Successful connection

Client to socket Write information

The server reads information

Client shutdown

Server side shutdown

Three handshakes

stay TCP/IP Agreement ,TCP The protocol establishes a reliable connection through three handshakes

The first handshake : The client tries to connect to the server , Send to server syn package ( Sync sequence number Synchronize Sequence Numbers),syn=j, Client access SYN_SEND Status waiting for server to confirm

The second handshake : The server receives the client syn Pack and confirm (ack=j+1), Send a... To the client at the same time SYN package (syn=k), namely SYN+ACK package , At this time, the server enters SYN_RECV state

The third handshake : The third handshake : Client receives server's SYN+ACK package , Send confirmation package to server ACK(ack=k+1), This package has been sent , Client and server access ESTABLISHED state , Complete three handshakes

You have a look at , The server socket With client socket The part that makes the connection is actually the famous three handshakes

socket Programming API

Mentioned earlier socket yes " open — read / Write — close " The realization of pattern , Have a brief understanding of socket What are provided API For application use , Or to TCP Agreement, for example , have a look Unix Under the socket API, Other languages are very similar (PHP Even the names are almost the same ), Here I will briefly explain the function and parameters of the method , If you are interested, you can look at the links in the blog reference or search online

int socket(int domain, int type, int protocol);

According to the specified address family 、 Data types and protocols to assign a socket Description words and the resources they use .

domain: Protocol family , Commonly used AF_INET、AF_INET6、AF_LOCAL、AF_ROUTE among AF_INET On behalf of the use of ipv4 Address

type:socket type , frequently-used socket Type a ,SOCK_STREAM、SOCK_DGRAM、SOCK_RAW、SOCK_PACKET、SOCK_SEQPACKET etc.

protocol: agreement . Common protocols are ,IPPROTO_TCP、IPPTOTO_UDP、IPPROTO_SCTP、IPPROTO_TIPC etc.

int bind(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

To assign a specific address in an address family to socket

sockfd:socket Description words , That is to say socket quote

addr: To bind to sockfd Agreement address for

addrlen: The length of the address

Usually the server will bind a well-known address when it starts ( Such as ip Address + Port number ), Used to provide services , The client can connect to the server through it ; And the client doesn't have to specify , The system automatically assigns a port number and its own ip Address combination . That's why the server is usually on listen We'll call bind(), And the client will not call , But in connect() The system randomly generates a .

int listen(int sockfd, int backlog);

monitor socket

sockfd: To monitor socket Description words

backlog: The corresponding socket The maximum number of connections that can be queued

int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);

Connect to a socket

sockfd: Client's socket Description words

addr: Server's socket Address

addrlen:socket The length of the address

int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);

TCP After the server listens to the client request , call accept() Function to receive the request

sockfd: Server's socket Description words

addr: Client's socket Address

addrlen:socket The length of the address

ssize_t read(int fd, void *buf, size_t count);

Read socket Content

fd:socket Description words

buf: buffer

count: Buffer length

ssize_t write(int fd, const void *buf, size_t count);

towards socket Write content , It's actually sending content

fd:socket Description words

buf: buffer

count: Buffer length

int close(int fd);

socket Mark to close , Make corresponding socket Reference count of descriptive words -1, When the reference count is 0 When , Trigger TCP The client sends a termination request to the server .

Socket Summary of more related articles

  1. iOS socket Summary 01

    One . Network protocols :TCP/IP.SOCKET.HTTP etc. The seven layers of the network are the physical layer from bottom to top . Data link layer . The network layer . Transport layer . The session layer . Presentation layer and application layer . The physical layer . The data link layer and the network layer are often referred to as the media layer , It's network engineering ...

  2. [ Weave a message framework ][ The Internet IO Model ]BIO

    Since it is related to the content of the Internet, we have to learn the Internet IO Model , The times are progressing , Technology is also improving , Take that kind of network IO The model already determines the size of the application Blocking IO(blocking IO) stay linux in , By default, all socket all ...

  3. [ Weave a message framework ][ The Internet IO Model ]Netty Reactor

    Strictly speaking Netty Reactor It's a design pattern , Just listen to the word pattern , Routine ha ha Reactor Chinese translated into “ Reactor ”. Look at the picture netty Processing flow 1.netty server At least two groups reactor. ...

  4. andriod socket Summary of development issues

    andriod socket Summary of development issues Personal information : Studied in Yan University undergraduate software project major Now senior ; My blog :google Search for "cqs_2012" Can ; Personal hobbies : Love data structures ...

  5. nginx+php-fpm Of socket Configuration summary

    About socket This article will not repeat , In the production environment socket The way , This paper describes its configuration . #cd /app/local/php# Switch to php Installation directory #mkdir run #chmod 777 ./ ...

  6. About Socket Summary of my experience

    Preface IM Communication is a well-known technology in the Internet world , Especially in the era of rapid development of mobile Internet, the development of this technology is also more hot , Among them, the old masterpieces are QQ and MSN, And the recent rise of wechat , silently , Yi Xin , Wait for the eye ...

  7. TCP/IP,http,socket, A long connection , Short connection —— Summary .

    source : TCP/IP What is it? ? TCP/IP It's a protocol group , It can be divided into three levels : The network layer . Transport layer and application layer . ...

  8. Socket Network programming --epoll Summary

    Previously used for I/O Multiplexing is used for convenience select function , but select This function is flawed . Because the number of concurrent connections it supports is limited ( Generally less than 1024), Because the arrays that the user processes are hard coded . The maximum value of this is FD_ ...

  9. 【Socket】Socket Network programming commonly used structure and function summary

    Noun analysis IP The purpose of address is to indicate the network card address of the computer , Every computer has a IP Address : Port refers to the number set in the computer to mark different programs accessing the network in the computer , It's not the port of the network card , It's the logical number of different programs , Not actually ...

Random recommendation

  1. C++ The knowledge base

    C++ The knowledge base Seckill multithreading .

  2. c# Generate MD5 character string

    public static string EncryptWithMD5(string source) { byte[] sor = Encoding.UTF8.GetBytes(source); MD ...

  3. Java synchronized Sync A brief explanation of each way

    In order to realize a function , In the tree structure , When modifying a node name , You need to modify the node full path attribute fields of all the child nodes of this node at the same time ( similar " Parent node name / Parent node name / Child node name / Child node name " Construction ). Because in ...

  4. Use diff Make patches

    1. Make patches Command format diff -uNr  oldfile.c newfile.c > x.patch 2. patch up Command format patch -p0 < x.patch To sum up : Single file ...

  5. ActionBarSherlock SlidingMenu Integrate , solve SlidingMenu example Of getSupportActionBar() The method can't solve the problem

    I downloaded it today SlidingMenu To study , I found the one inside example Out of commission , Always prompt BaseActivity I can't find getSupportActionBar() Method , To Github It turns out that ...

  6. poj-------(2240)Arbitrage( shortest path )

    Arbitrage Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 15640   Accepted: 6563 Descri ...

  7. WebSocket with Flask

    from : WebSocket with Flask HTML5 before ,HTML Not yet  Web ...

  8. adopt ajax get json Data format conversion

    In some cases json The data could be string Type of , It needs to be formatted as json Object is easy to parse . a) Native js adopt ajax Acquired json The data returned at this time is... By default string Type , So we need to use eval( ...

  9. ASProtect.SKE.2.11 stolen code Decrypt

    About ASProtect.SKE.2.11 stolen code There have been a lot of articles on , Today I want to talk about the details of it in detail , To my brothers who love cracking . stolen code It is not fearful ! ASProtect.SKE ...

  10. install MYSQL exec: g++: not found Report errors

    terms of settlement :   yum install -y gcc-c++