Serial programming Python, pyserial

1. Serial programming Python, pyserial 

Website: http://www.douban.com/group/topic/7400483/

import sys,os
import serial
ser=serial.Serial(port='COM5',baudrate=9600,bytesize=8,parity='N',stopbits=1,timeout=5)

str=""
while ser.isOpen():
x=ser.readline(200)
print x,
str = str + x

ser.close()

 

2, python socket programming UDP

Website: http://www.2cto.com/kf/201412/360043.html

server.py

import socket
 
BUF_SIZE = 1024
server_addr = ('127.0.0.1',8888)
server = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_addr)
while True:
     print "waiting for data"
     data,client_addr = server.recvfrom(BUF_SIZE)
     print 'Connected by ',client_addr,' Receive data : ',data
     server.sendto(data,client_addr)
server.close()

 client.py

 

import socket
import struct
 
BUF_SIZE = 1024
server_addr = ('127.0.0.1',8888)
client = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
 
while True:
     data = raw_input("Please input some string > ")
     client.sendto(data,server_addr)
     data,addr = client.recvfrom(BUF_SIZE)
     print "Data : ",data
client.close()

 3. Examples of TCP communication and socketserver framework use of python network programming

1) TCP is a reliable connection-oriented protocol. Before one party sends data, a connection must be established between the two parties. The establishment process needs to go through three handshakes. After the communication is completed, the connection needs to go through four handshakes. It is caused by the half-close of TCP. One party needs to send a FIN to terminate the connection in this direction after completing the data transmission. A TCP connection can still send data after receiving a FIN, but the application rarely does this. The following is The process of establishing and tearing down a TCP connection:


 

2) python can realize the programming of TCP server and client, the following is the code:

Service-Terminal:

#!/usr/bin/env python
import socket
host="localhost"
port=10000
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(5)
while 1:
 sock,addr=s.accept()
 print "got connection form ",sock.getpeername()
 data=sock.recv(1024)
 if not data:
  break
 else:
  print data

 
 
Client:

#!/usr/bin/env python
import socket
host="localhost"
port=10000
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send("hello from client")
s.close()

 3) Write a TCP server using the socketserver framework

    The Socketserver module can simplify the writing of network servers. It includes four server classes, TCPServer uses TCP protocol, UDPServer uses UDP protocol, and two less commonly used ones, namely UnixStreamServer and UnixDatagramServer, these two classes are only in the unix environment it works.

    To use server programming, you need to perform the following steps. First, create a request handle class, which inherits from the BaseRequestHandler class. After creating this class, rewrite its handle method, then instantiate the server class, and pass the host name, port number and handle class. Give it, and then call the server_forever() method to handle the request.

   Server using socketserver framework:

import SocketServer
host=''
port=10000
class Handler(SocketServer.StreamRequestHandler):

 def handler(self):
  addr=self.request.getpeername()
  print "got connection from",addr
  self.wfile.write("connected")

server=SocketServer.TCPServer((host,port),Handler)
server.serve_forever()

 The above socketserver server can only process one request. If you want to process multiple requests, you can use forking or threading to realize multi-process or multi-threaded server. Here is the server code using forking and threading:

Servers using forking:

from SocketServer import TCPServer,ForkingMixIn,StreamRequestHandler
class Server(ForkingMixIn,TCPServer):pass
class Handler(StreamRequestHandler):

 def handle(self):
  addr=self.request.getpeername()
  print "got connection from",addr
  self.wfile.write('connected')

server=Server((''.10000),Handler)
server.serve_forever()

 Using a multithreaded server:

 

from SocketServer import TCPServer,ThreadingMixIn,StreamRequestHandler
class Server(ThreadingMixIn,TCPServer):pass
class Handler(StreamRequestHandler):
 def handle(self):
  addr=self.request.getpeername()
  print "got connection from",addr
  self.wfile.write("connected")

server=Server(('',10000),Handler)
server.serve_forever()

 4. Python Tcp small example

Server code server.py
#coding:utf-8
import socket
import datetime
 
"""
define basic information
"""
HOST = "" #host
PORT = 23151 #port
ADD = (HOST, PORT)
BUFFERSIZE = 1024 #buffer size
 
"""
Create socket, bind address and start listening
"""
TcpSerSock = socket.socket (socket.AF_INET, socket.SOCK_STREAM) # 创建 socket
TcpSerSock.bind(ADD) #Bind address and port
TcpSerSock.listen(10) #Start listening, the number of listening should not exceed 10 at the same time
 
"""
After socekt is built, start the connection and data transmission
"""
print "The server is waiting for a connection..."
TcpCliSock, addr = TcpSerSock.accept() #Start connection
while True:
    date = TcpCliSock.recv(BUFFERSIZE) #Accept data
    if date: #If data is received
        curTime = datetime.datetime.now() #Get the current time format is: datetime.datetime(2012, 3, 13, 1, 29, 51, 872000)
        curTime = curTime.strftime('%Y-%m-%m %H:%M:%S') #Conversion format
        print "%s  %s" % (addr, curTime)
        print date
        # send data
        sendDate = raw_input("input:")
        TcpCliSock.send('%s' % (sendDate)) #Send data   
        if date == '88':
            break  
     
"""
When the connection is complete, close the socket
"""
print "server close"
TcpCliSock.close()
TcpSerSock.close()
 
 
 
 
 
 
 
Client code client.py
#coding:utf-8
import socket
import datetime
 
"""
Define basic information: the host and port should be the same as the server
"""
HOST = "localhost" #service its address
PORT = 23151 #Server port
BUFFERSIZE = 1024
ADDR = (HOST, PORT)
 
"""
establish a socket, start a connection
"""
TCPClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
TCPClient.connect(ADDR) #Connect to the server
 
"""
start data transfer
"""
while True:
    senddate = raw_input("input:")
    if senddate:
        TCPClient.send('%s' % (senddate)) #Send data
         
    recvdate = TCPClient.recv(BUFFERSIZE) #Accept data
    curTime = datetime.datetime.now() #Get the current time format is: datetime.datetime(2012, 3, 13, 1, 29, 51, 872000)
    curTime = curTime.strftime('%Y-%m-%m %H:%M:%S') #Conversion format
    print "%s  %s" % (HOST, curTime)
    print  recvdate
    if recvdate == '88':
            break  
     
"""
When the transfer is complete, close the socket
"""
print "client close"
TCPClient.close()

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326756182&siteId=291194637