Python socket programming

Source: Internet
Author: User

Establishing a server connection requires six steps.

The 1th step is to create the socket object. Call the socket constructor.

Socket=socket.socket (Familly,type)
The value of family can be Af_unix (UNIX domain for interprocess communication on the same machine) or af_inet (TCP and UDP for IPV4 Protocol), as for the type parameter, SOCK_STREAM (stream socket), or Sock_ Dgram (data message socket), SOCK_RAW (RAW socket).

The 2nd step is to bind (assign) the socket to the specified address, socket.bind (address)

Address must be a two-element tuple, ((Host,port)), host name or IP address + port number. If the port number is being used or reserved, or if the hostname or IP address is wrong, a Socke.error exception is thrown.

3rd step, after binding, you must have the socket ready to accept the connection request.

Socket.listen (Backlog)
The backlog specifies the maximum number of connections, at least 1, after the connection request is received, the requests must be queued, and if the queue is full, the request is rejected.

4th, the server socket waits for the client to request a connection through the socket's Accept method:

Connection,address=socket.accept ()
When the Accept method is called, the socket enters the ' waiting ' (or blocked) state. When a client requests a connection, the method establishes the connection and returns the server. The Accept method returns a tuple that contains two elements, such as (connection,address). The first element (connection) is the new socket object through which the server communicates with the customer, and the second element (address) is the customer's Internet address.

The 5th step is the processing phase

The server and the customer communicate (transmit data) through the Send and recv methods. The server calls send and sends a message to the customer in string form. The Send method returns the number of characters that have been sent. The server uses the Recv method to accept information from the customer. When calling recv, you must specify an integer to control the maximum amount of data that is accepted by this call. The Recv method enters the ' Blocket ' state when the data is accepted, and finally returns a string that represents the received data. If the amount sent exceeds the allowable recv, the data is truncated. The excess data will be buffered on the receiving end. When you call recv later, the extra data is removed from the buffer.

6th step, the transfer ends, the server calls the socket's Close method to close the connection.


Establishing a simple client connection requires 4 steps.


1th step, create a socket to connect to the server Socket=socket.socket (Family,type)

2nd step, connect to Server Socket.connect ((host,port)) using the socket's Connect method

3rd, the client and server communicate via the Send and recv methods.

At the end of the 4th step, the customer closes the connection by calling the Close method of the socket.

server.py
#!/usr/bin/env python
# Tcp-server
Import socket
Import time

Host= "
port=8001
bufsiz=1024

Sock=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Sock.bind ((Host,port))
Sock.listen (5)
While True:
print ' Waiting for connection ... '
Connection,address=sock.accept ()
Print (' Connection from ', address)
While True:
Try
DATA=CONNECTION.RECV (Bufsiz)
Except
Print (e)
Connection.close ()
Break
If not data:
Break
s= ' hi,you send me: [%s]%s '% (Time.ctime (), Data.decode (' UTF8 '))
Connection.send (S.encode (' UTF8 '))
Print ([Time.ctime ()], ': ', Data.decode (' UTF8 '))
Connection.close ()
Sock.close ()

client.py
#!/usr/bin/env python
# tcp-client
Import socket
Import Sys

Host= ' 127.0.0.1 '
port=8001
bufsiz=1024
Client=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
Client.connect ((Host,port))
While True:
Data=raw_input ('---')
If data== ' Quit ':
Sys.exit ()
Client.send ('%s\r\n '% data.encode (' UTF8 '))
D=CLIENT.RECV (Bufsiz)
Print (D.decode (' UTF8 '))

This article is from the "Small Micro" blog, please make sure to keep this source http://guoshiwei.blog.51cto.com/2802413/1923876

Python socket programming

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.