Python socket programming, pythonsocket

Source: Internet
Author: User

Python socket programming, pythonsocket

Write a little bit every day. One day, the salted fish will become more salty.

 

File Reference: Click Here (http://www.cnblogs.com/aylin/p/5572104.html)

Main content:

1. socket

2. socketserver

 

I. socket

Socket Introduction

Socket originated from Unix, and one of the basic philosophies of Unix/Linux is "Everything is a file". For files, use the [open] [read/write] [close] mode to operate, this is also true for the socket implementation mode. It can be seen as a special file mode. The specific process of creating a connection, sending a message, and closing a connection is shown in:

 

The code example is as follows:

Server

Import socketport = 8888 host = "127.0.0.1" # create a socket description character sk = socket. socket () # name socket sk. bind (host, port) # Listen to the client request sk. listen (5) while True: # Wait for the client to connect, conn, address = sk. accept () # returns conn to the client. send ("welcom !!!!! \ N ") while True: # receive client message content = conn. recv (1024) if content = "exit": break else: data = raw_input ("please input:") # respond to the message to the client conn. send (data)
Server

Client

Import sockethost = "127.0.0.1" port = 8888 # create a socket character description cl = socket. socket () # connect to the server cl. connect (host, port) while True: # receive Server Response content = cl. recv (1024) flag = 1 while flag: data = raw_input ("please input:") # send a message to the server cl. send (data) if data = "exit": flag = 0 else: content = cl. recv (1024) # disable connection cl. close () break
Client

 

Server common functions

Sk. bind (address)

Bind the socket to the address. The address must be transmitted as a tuple.

Sk. listen (n)

Listening address. n indicates the maximum number of connections that can be suspended. The maximum value of n is 5.

Sk. accpet ()

Accept client connection requests and return (conn, address). conn is a new socket object and can be used to interact with the client. Address is the client address. This step is blocked and will wait until you receive the client connection request.

Sk. close ()

Close connection

Sk. connect (address)

Connect to the socket at address. The address format is tuples. If a connection error occurs, a socket exception is thrown.

Sk. connect_ex (address)

Same as above, only connection error return code

Sk. recv (bufsize)

Accept socket data. The data is returned as a string. The bufsize specifies the maximum number of messages that can be received.

Sk. recvfrom (bufsize)

Similar to recv (), but the returned value is a tuples (data, address)

Sk. send (string)

Send data. The returned value is the length of the sent data, which may be less than the string length.

Sk. sendall (string)

Send data. If all data is sent, None is returned. If the sending fails, an exception is thrown.

Sk. sendto (string, address)

Send data to a specified address

Sk. settimeout (timeout)

Sets the superperiod of socket operations. Unit: s and type: Floating Point.

 

Simple socket instance

TCP file upload:

import socketimport sysimport osip_port = ('127.0.0.1', 8888)sk = socket.socket()sk.connect(ip_port)container = {'key': '', 'data': ''}while True:    input = raw_input('path:')    cmd, path = input.split('|')    file_name = os.path.basename(path)    file_size = os.stat(path).st_size    sk.send(cmd + "|" + file_name + '|' + str(file_size))    send_size = 0    f = file(path, 'rb')    Flag = True    while Flag:        if send_size + 1024 > file_size:            data = f.read(file_size - send_size)            Flag = False        else:            data = f.read(1024)            send_size += 1024        sk.send(data)    f.close()sk.close()
Client
Import socketdef recv_data (): port = 8888 host = "127.0.0.1" # create a socket description character sk = socket. socket () # name socket sk. bind (host, port) # Listen to the client request sk. listen (5) conn, address = sk. accept () while True: pre_data = conn. recv (1024) # obtain the request method, file name, file size cmd, file_name, file_size = pre_data.split ('| ') # size of the received file recv_size = 0 # concatenate the uploaded file path f = file ("B .txt", 'wb ') Flag = True while Flag: # Not uploaded, if int (file_size)> recv_size: # A maximum of 1024 data records can be received, which may be less than 1024 data = conn. recv (1024) recv_size + = len (data) # exit the loop else: recv_size = 0 Flag = False continue # Write File f. write (data) print 'upload successed. 'F. close () if _ name _ = "_ main _": recv_data ()
Server

UDP:

import socketaddress  = ("127.0.0.1",8880)cl = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)while True:    data = raw_input("input:")    if data == "exit":        break    cl.sendto(data,address)
Client
import socketaddress=("127.0.0.1",8880)sk = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,0)sk.bind(address)while True:    data = sk.recv(1024)    print data
Server

I. socketserver

  The limitation of socket is that the process of receiving data is blocked, that is to say, the communication between socket modules is one-to-one. For example, when you call, A is talking to B. You can establish A connection with A only after the AB call is over. This obviously cannot meet the requirements of the server, but the socketserver can indeed meet the above requirements.

The flowchart is as follows:

Socketserver is the Socket server that can process requests from multiple clients. Because when each client requests, the server creates a thread to communicate with the client.

Example:

Import socketobj = socket. socket () obj. connect ("127.0.0.1", 8080) ret_bytes = obj. recv (1024) ret_str = str (ret_bytes) print (ret_str) while True: indium = raw_input ("Hello, what's your problem? \ N >>> ") if indium =" exit ": obj. sendall (bytes (indium) break else: obj. sendall (bytes (indium) ret_bytes = obj. recv (1024) ret_str = str (ret_bytes) print (ret_str)
Client
Import socketserverclass Myserver (socketserver. baseRequestHandler): def handle (self): conn = self. request conn. sendall ("Hello, I am a robot") while True: ret_bytes = conn. recv (1024) if ret_bytes = "exit": break conn. sendall ("hello, everyone") if _ name _ = "_ main _": server = socketserver. threadingTCPServer ("127.0.0.1", 8080), Myserver) server. serve_forever ()
Server

 

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.