Basic Python Socket edit this introductory introduction

Source: Internet
Author: User
Tags bind error handling socket in python

  Basic Python Socket edit this introductory introduction

This article mainly introduces the basic Python socket programming primer, including the most basic content such as sending and receiving information, need friends can refer to the following

This article describes the use of Python for socket network programming, assuming that the reader has the basic knowledge of network programming and Python basic syntax knowledge, the code in this article, if not stated, is run under Python 3.4.

Python socket functions are encapsulated in the socket library, to use the socket, remember to import the Socket,socket library detailed introduction See official documentation.

Create a socket

First create a socket and use the socket function in the socket library to create it.

?

1 Import socket

?

1 2 # Create an INET, STREAM socket s = socket.socket (socket.af_inet, socket. SOCK_STREAM)

The default values for the first two parameters of a TCP Socket,socket.socket function created in the example are Socket.af_inet and Socket.sock_stream, which can be written directly as Socket.socket when the TCP socket is created ( )。

Connecting to a server

Using the Connect function of the socket is connected to the server, several of the following parameters are valid.

?

1 2 3 S.connect ((' localhost ', 8000)) S.connect ((' 127.0.0.1 ', 8000)) S.connect ((' www.baidu.com ', 80))

Send data

Send data two methods send and sendall,send do not guarantee that all the data is sent, it returns the length of the sent data, and the program loops through the data until all the data is sent.

?

1 2 3 4 5 6 7 8 def mysend (S, msg): Total_len = Len (msg) total_sent = 0 while total_sent < total_len:sent = S.send (msg[total_sent:]) I F sent = = 0:raise RuntimeError ("Socket Connection broken") Total_sent + = Sent

Sendall can guarantee that all the data has been sent, unless there is an error in the sending process, it is actually looping through the data until all the data is sent.

Here's another place to take a special look, starting with an example:

?

1 2 3 4 Import socket s = Socket.socket () s.connect (' www.baidu.com ', #) S.sendall (' Test ')

It's all the stuff that's been said, nothing special, execute the code in Python 2 and Python 3, and the result is:

?

1 2 3 4 5 # Python 2.7 >>> import socket >>> s = socket.socket () >>> s.connect (' www.baidu.com ', ;>> s.sendall (' test ')

Execution succeeded in Python 2.

?

1 2 3 4 5 6 7 8 # Python 3.4 >>> Import socket >>> s = socket.socket () >>> s.connect (' www.baidu.com ', ;>> s.sendall (' Test ') traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ' STR ' does not support the buffer interface

An exception occurred in Python 3.

The same code to change the environment can not be implemented, I did not write wrong Ah, angry smashed the computer. Well, you did not write wrong, the environment has changed, leading to changes in the results of the official note.

Receive data

To receive data using the RECV function:

?

1 data = S.RECV (4096)

The bytes object is returned in Python 3, and string is returned in Python 2. Note The data length returned by the function is less than or equal to the length specified by the parameter, and you need to iterate over the data to receive the specified length of data.

?

1 2 3 4 5 6 7 8 9 10 def myreceive (S, msglen): chunks = [] Bytes_recd = 0 while bytes_recd < Msglen:chunk = S.recv (min msglen-bytes_recd, 2048)) If chunk = = B ': Raise RuntimeError ("Socket Connection Broken") Chunks.append (chunk) BYTES_RECD = Bytes_recd + len (chunk) return B '. Join (chunks)

Close connection

You can use close to turn off the socket connection when the connection is no longer needed, and no further action will be allowed after the closed connection. When a socket is reclaimed, it is automatically closed, but do not rely on this mechanism and actively close when you do not need a socket.

Service side

Steps for server-side program execution:

1. Create a service port socket

1. Bind the server socket to the specified address and port

1. Listening connection

1. Accept client Connections

1. Processing the data of the client

1. Close client connections

A simple example of ECHO server:

?

1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15 Import socket HOST = ' PORT = 10022 s = socket.socket (socket.af_inet, socket. Sock_stream) S.bind ((HOST, PORT) S.listen () conn, addr = S.accept () while true:data = CONN.RECV (1024) if not data:bre AK Conn.sendall (data) conn.close ()

Client program:

?

1 2 3 4 5 6 7 8 9 10 11 Import socket HOST = ' localhost ' PORT = 10022 s = socket.socket (socket.af_inet, socket. Sock_stream) S.connect ((HOST, PORT) s.sendall (b ' Hello socket ') data = S.RECV (1024) print (' Received ', repr (data)) S.close ()

Error handling

Errors during socket processing throw exceptions, and socket-related exceptions are:

-Socket.error

-Socket.herror

-Socket.gaierror

-Socket.timeout

?

1 2 3 4 5 6 7 8 9 10 11 Import Socket HOST = None PORT = 10022 try:s = socket.socket (socket.af_inet, socket. Sock_stream) S.bind ((HOST, PORT) S.listen Except:socket.error as Msg:print (msg)
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.