Basics of socket programming for Python programming

Source: Internet
Author: User

Python socket programming, first requires the import socket module

First create a Socket object

The first of these parameters is usually the following

1, socket.af_inet usually refers to the IP address, 2, Socket.af_unix usually refers to the local domain socket communication.

A second parameter

1, socket. Sock_stream stream Socket (TCP), 2, socket. Sock_dgram datagram Sockets (UDP)

Binding the specified IP and port

Sock.bind (address);

Parameters:

The socket created earlier uses the Af_inet type, where address is a two-element tuple.

Address is in the format (host,port) and host Ip,port is the port.

Like what:

Sock.bind (("172.25.81.16", 33306));

To set the size of the listening queue:

Sock.listen (backlog);

Parameters:

The backlog is used to set the size of the connection queue, with a minimum value of 1.

Like what:

Sock.listen (10);

Receive client connections:

Connect,address = Sock.accept ();

return value:

Connect is the connection established with the client, and subsequent communication relies on it to complete, buf=connect.recv (len) or Connect.send (BUF), and so on.

Address is the location information for the client, in the format (host,port)

Receiving and sending messages:

Receive:

BUF = connect.recv (len);

return value:

The content of the message received;

Receive length len;

For example:

BUF = CONNECT.RECV (1024);

Send:

buf= "Hello World";

Connect.send (BUF);

Link to server:

Sock.connect (address);

Parameters:

Address on the server side, in the format (HOST,IP).

For example:

Sock.connect ((192.168.1.1,8080));

To close the connection:

Sock.close ();

Basics of socket programming for Python programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.