Python socket Coding

Source: Internet
Author: User
Tags socket connect

 

To compile a server in Python, follow these steps:
1. The first step is to create a socket object. Call the socket constructor. For example:
Socket = socket. socket (family, type)
The family parameter represents the address family, which can be af_inet or af_unix. The af_inet family includes Internet addresses, and the af_unix family is used for communication between processes on the same machine.
The type parameter represents the socket type, which can be sock_stream (stream socket) and sock_dgram (datagram socket ).
2. The second step is to bind the socket to the specified address. This is implemented through the bind method of the socket object:
Socket. BIND (address)
The address of a socket created by af_inet must be a dual-element tuple in the format of host and port ). Host indicates the host, and port indicates the port number. If the port is in use, the host name is incorrect, or the port is retained, the bind method will cause a socket. error exception.
3. Step 3: Use the listen method of Socket socket to receive connection requests.
Socket. Listen (backlog)
Backlog specifies the maximum number of customers allowed to connect to the server. The value must be at least 1. After receiving the connection request, these requests need to be queued. If the queue is full, the request is rejected.
4. Step 4: the server socket waits for the customer to request a connection through the socket accept method.
Connection, address = socket. Accept ()
When the accept method is called, the socket enters the "Waiting" status. When a customer requests a connection, the method establishes a connection and returns it to the server. The accept method returns a triple (connection, address) containing two elements ). The first element connection is the new socket object, and the server must communicate with the customer through it; the second element address is the customer's Internet address.
5. The fifth step is the processing stage. The server and client communicate (transmit data) through the send and Recv methods ). The server calls send and uses a string to send messages to the customer. The send method returns the number of sent characters. The server uses the Recv method to receive information from the customer. When calling Recv, the server must specify an integer, which corresponds to the maximum data volume that can be received through this method call. The Recv method enters the "blocked" status when receiving data, and returns a string that indicates the received data. If the amount of data sent exceeds the Recv limit, the data will be truncated. The excess data is buffered at the receiving end. When Recv is called in the future, excess data will be deleted from the buffer zone (and any other data that the customer may send since the last Recv call ).
6. When the transmission ends, the server calls the close method of socket to close the connection.

Follow these steps to write a client in Python:
1. Create a socket to connect to the server: Socket = socket. socket (family, type)
2. Use the socket connect method to connect to the server. For the af_inet family, the connection format is as follows:
Socket. Connect (host, Port ))
Host indicates the server host name or IP address, and port indicates the port number bound to the server process. If the connection is successful, the customer can communicate with the server through the socket. If the connection fails, the socket. error exception will occur.
4. In the processing phase, the customer and the server will communicate with the Recv method through the send method.
5. When the transmission ends, the customer calls the close method of socket to close the connection.

Example:
Server. py

Import sockets = socket. socket () s. BIND ('0. 0.0.0 ', 5200) # IP address and port number S. listen (5) CS, address = S. accept () print 'got connected from ', addresscs. send ('byebye ') Ra = cs. recv (512) print RACs. close ()

Client. py

Import sockets = socket. socket () s. connect ('2017. 0.0.1 ', 5200) # Same as the server program IP address and port number data = S. recv (512) s. send ('hihi') s. close () print 'the data already ed', Data
 

----------

 

Both TCP socket and UDP socket are created through socket. socket (socket. af_inet, socket. sock_stream/sock_dgram ).

The first parameter is usually set to socket. af_inet.

Second Parameter

TCP: sock_stream

UDP: sock_dgram

 

Simple code:

Client. py

import socket
import time

if __name__=='__main__':
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
addr=('localhost',2000)
sock.connect(addr)
time.sleep(2)
try:
while True:
sock.send(raw_input('>>'))
buff=sock.recv(1024)
print 'get: %s %s' % (buff,time.ctime())
except Exception,e:
print "Error:",e
sock.close()
Copy code

 

Services. py

  

import socket
import datetime

if __name__=='__main__':
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('127.0.0.1',2000))
sock.listen(5)
while True:
connection,address=sock.accept()
connection.settimeout(10000)
while True:
try:
buf=connection.recv(1024)
print 'get: %s %s' % (buf,datetime.datetime.now())
if buf=='exit':
break
connection.send(raw_input('>>'))
except socket.timeout:
print 'time out'
connection.close()
Copy code

The UDP protocol is similar to the TCP protocol, but the keywords are different.

 

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.