C++ socket and compare with linux socket

First posted Source:

For Server:

 

 

 For Client:

 

 

 Results are as follows:

First run the server, it will prompt the binding is successful, and waits for the client connection:

 

 Run client after the two sides began to interoperate message:

 

 

Analysis and comparison:

 Socket general process shown below

 

 

For the server is concerned, it is the process

--- >> bind socket to create a socket and listening port number --- >> connection request that port number --- >> --- waits for a client to accept the message or send a message >>

And this is the client:

Create a socket --- >> connect to the specified server port --- >> to accept the message or send a message

After the end of the connection, both must remember to close the socket.

But in class we wrote in the analysis of teacher linux socket using #include <sys / socket.h>

Narrations and the use of C ++ #include <winsock.h> also similar processes

I have to say is probably the difference needs to be initialized before programming winsock WSAStartup

Corresponding exit cleanup requires the use of WSAClearup ()

And the difference between the names of some functions, such as under closesocket () and Linux close ()

 

 

 Next analyzes the socket API

1、socket

 

 It has three parameters, namely domin, type and Protocol, i.e. the protocol field, socket type and protocol

We can also find the corresponding macro definitions in the header file winsock.h:

Domin: protocol family determines the type of socket address, the address must be in the corresponding communication, determines the composition as AF_INET use ipv4 address (32 bit) and port number (16) is.

 

 protocol: protocol is what we learned tcp, udp, etc.

 

 2、bind

After initialization socket descriptor created, you need to bind () to a specific address family addresses assigned to the socket

 

 如图,利用SOCKADDR_IN 定义变量并设置好对应的协议和端口号之后,紧接着调用bind( )函数将其绑定在socket中

故bind函数的三个参数是 socket 、 一个const struct sockaddr *指针,指向要绑定给sockfd的协议地址 和 地址长度

图中我们使用的是AF_INET即ipv4协议,那么对应的协议地址结构如下:

 

 

3、listen

socket()函数创建的socket默认是一个主动类型的,listen函数将socket变为被动类型的,等待客户的连接请求。
如果作为一个服务器,在调用socket()、bind()之后就会调用listen()来监听这个socket。

 

 第一个参数socket

 第二个参数表示相应的socketk可以排队的最大连接个数

 

4、connect

 

 从图中可以看出,connect( ) 函数的参数列表和 bind( )函数很相似

 但它用于客户端,客户端调用connect ()函数来与服务器发出连接,这时服务器的listen( )函数便会收到它的连接请求

 

5、accept

 

 服务器端依次调用socket()、bind()、listen()之后,就会监听指定的socket地址了。

 而客户端依次调用socket()、connect()之后就等于是向服务器发送了一个连接请求,这时服务器可以使用accept( )来接受这个请求。

 它的参数列表依旧和bind( )类似,但是中间的addr地址返回的是客户端的协议地址,而bind()的addr地址是指向要绑定的socket的协议地址。

 

6、recv 和 send

  即发送和接收

 

7、close

  当所有的操作完成后,需要使用closesockt()来关闭所有的连接。

 

 

Guess you like

Origin www.cnblogs.com/qwertyue/p/11988899.html