Basic Python socket programming tutorial, pythonsocket

Source: Internet
Author: User
Tags socket connect

Basic Python socket programming tutorial, pythonsocket

This article describes how to use Python for Socket network programming. If you already have basic network programming knowledge and basic Python syntax knowledge, the code in this article runs under Python 3.4 if it is not described.

The socket function of Python is encapsulated in the socket library. To use socket, remember to import socket first. For details about the socket library, see the official documentation.
Create Socket

First, create a socket and use the socket function in the socket library.

import socket
# create an INET, STREAM sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

In this example, a TCP socket is created. The default values of the first two parameters of the socket. socket function are socket. AF_INET and socket. SOCK_STREAM. When creating a TCP socket, you can directly write it as socket. socket ().
Connect to the server

Use the socket connect function to connect to the server. The following parameters are valid.

s.connect(('localhost', 8000))s.connect(('127.0.0.1', 8000))s.connect(('www.baidu.com', 80))

Send data

There are two methods to send data: send and sendall. send cannot ensure that all data is sent completely. It returns the length of the sent data, the program sends data cyclically until all data has been sent.

def mysend(s, msg):  total_len = len(msg)  total_sent = 0  while total_sent < total_len:    sent = s.send(msg[total_sent:])    if sent == 0:      raise RuntimeError("socket connection broken")    total_sent += sent

Sendall ensures that all data has been sent. Unless an error occurs during the sending process, sendall actually sends data cyclically until all data is sent completely.

Here we also want to talk about a special point, starting with an example:

import sockets = socket.socket()s.connect(('www.baidu.com', 80))s.sendall('test')

All of the things mentioned above are nothing special. Execute the above Code in Python 2 and Python 3 respectively, and the result is:

# Python 2.7>>> import socket>>> s = socket.socket()>>> s.connect(('www.baidu.com', 80))>>> s.sendall('test')

Python 2 is successfully executed.

# Python 3.4>>> import socket>>> s = socket.socket()>>> s.connect(('www.baidu.com', 80))>>> 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.

I couldn't execute the same code in another environment. I didn't make a mistake, so I was so angry with my computer. Well, you did not make a mistake. It is because the environment has changed and the result has changed. Please go to the official instructions.
Receive data

Use the recv function to receive data:

data = s.recv(4096)

In Python 3, a bytes object is returned, and in Python 2, a string is returned. Note that the length of data returned by the function is smaller than or equal to the length specified by the parameter. To receive data of the specified length, you need to receive data cyclically.

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

When the connection is no longer needed, you can use close to close the socket connection. After the connection is closed, no operation can be performed. When a socket is recycled, it is automatically closed, but do not rely on this mechanism. When the socket is not required, it is automatically closed.
Server

Steps for executing the server program:
1. Create a server socket
1. Bind the server socket to the specified address and port
1. Listen for connection
1. Accept Client Connection
1. Process client data
1. disable Client Connection

A simple echo server example:

import socketHOST = ''PORT = 10022s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.bind((HOST, PORT))s.listen(10)conn, addr = s.accept()while True:  data = conn.recv(1024)  if not data:    break  conn.sendall(data)conn.close()

Client Program:

import socketHOST = 'localhost'PORT = 10022s = 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

When an error occurs during socket processing, an exception is thrown. socket-related exceptions include:

  • -Socket. error
  • -Socket. herror
  • -Socket. gaierror
  • -Socket. timeout
import socketHOST = NonePORT = 10022try:  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  s.bind((HOST, PORT))  s.listen(10)except: socket.error as msg:  print(msg)

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.