Socket programming of Python Web study notes

Python provides two basic socket modules.

   The first is Socket, which provides the standard BSD Sockets API.

   The second is SocketServer, which provides server-centric classes that simplify the development of web servers.

 

The following is the function of the Socket module:

 

1. Socket  type

Socket format:

socket(family,type[,protocal])  creates a socket with the given address family, socket type, and protocol number (default 0 ).

 

2. Socket function

important point:

1 ) When TCP sends data, a TCP connection has been established, so there is no need to specify an address. UDP is connectionless, and each time you send it, you need to specify who it is sent to.

2 ) The server and client cannot directly send lists, tuples, and dictionaries. Requires stringified repr(data) .

 

3. Socket programming ideas

TCP server:

Create a socket, bind the socket to the local IP and port

   #  socket.socket (socket.AF_INET, socket.SOCK_STREAM), s.bind ()

Start listening for connections #s.listen()

Enter the loop and continuously accept the client's connection request #s.accept()

Then receive the incoming data and send it to the other party #s.recv() , s.sendall()

After the transfer is complete, close the socket #s.close()

 

 

TCP client:

 

Create a socket and connect to the remote address

 

       #  socket.socket (socket.AF_INET, socket.SOCK_STREAM), s.connect ()

 

Send data and receive data after connecting # s.sendall(), s.recv()

 

After the transfer is complete, close the socket #s.close()

 

 

4. Socket programming server code:

import socket   #socket模块
import commands   #执行系统命令模块
HOST='10.0.0.245'
PORT=50007
s= socket.socket(socket.AF_INET,socket.SOCK_STREAM)   #定义socket类型,网络通信,TCP
s.bind((HOST,PORT))   #套接字绑定的IP与端口
s.listen(1)         #开始TCP监听
while 1:
       conn,addr=s.accept()   #接受TCP连接,并返回新的套接字与IP地址
       print'Connected by',addr    #输出客户端的IP地址
       while 1:
                data=conn.recv(1024)    #把接收的数据实例化
               cmd_status,cmd_result=commands.getstatusoutput(data)   #commands.getstatusoutput执行系统命令(即shell命令),返回两个结果,第一个是状态,成功则为0,第二个是执行成功或失败的输出信息
                if len(cmd_result.strip()) ==0:   #如果输出结果长度为0,则告诉客户端完成。此用法针对于创建文件或目录,创建成功不会有输出信息
                        conn.sendall('Done.')
                else:
                       conn.sendall(cmd_result)   #否则就把结果发给对端(即客户端)
conn.close()     #关闭连接

 

 

5、Socket编程之客户端代码:

 import socket
HOST='10.0.0.245'
PORT=50007
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)      #定义socket类型,网络通信,TCP
s.connect((HOST,PORT))       #要连接的IP与端口
while 1:
       cmd=raw_input("Please input cmd:")       #与人交互,输入命令
       s.sendall(cmd)      #把命令发送给对端
       data=s.recv(1024)     #把接收的数据定义为变量
        print data         #输出变量
s.close()   #关闭连接

 

 

 

 

参考

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324693125&siteId=291194637