Python 9th Day

Python Socket

Socket 是一切网络通信的基础,socket 是一个网络通信两端的虚拟端点 (virtual endpoints), socket 可以被配置为一个 server that listen for incoming messages. 也可以是一个连接其他应用的客户端。在服务端和客户端各有一个 TCP/IP socket, 互相 connected and communication is bi-directional.

socket () 返回一个 socket object, 常量 (Constants):

协议族:

socket.AF_UNIX: 本地

socket.AF_INET: IPv4

socket.AF_INET6: IPv6

套接字类型:

socket.SOCK_STREAM: connection oriented TCP protocol

socket.SOCK_DGRAM: connection oriented UDP protocol

socket.SOCK_RAW: 网络层的原始协议

socket.SOCK_SEQPACKET: 可靠的有序的分组服务

创建套接字

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

连接到一个 Server 上:

import socket
import sys

try:
    # create an AF_INET, STREAM socket (TCP)
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
    print('Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1])
    sys.exit();
 
print 'Socket Created'

host = 'www.google.com'
port = 80
 
try:
    remote_ip = socket.gethostbyname( host )
except socket.gaierror:
    # could not resolve
    print('Hostname could not be resolved. Exiting')
    sys.exit()
     
print('Ip address of ' + host + ' is ' + remote_ip)
 
#Connect to remote server
s.connect((remote_ip , port))
 
print('Socket Connected to ' + host + ' on ip ' + remote_ip)

上面的程序创建了一个 socket 然后连接远程主机。连接的概念只应用于 SOCK_STREAM/TCP 类型的套接字,连接意味着可以有很多相互独立的数据管道。其他例如 UDP, ICMP, ARP 没有连接的概念,这些不基于连接的通信意味着会持续的接收和发送任何 packets.

一次完整的 socket 通信 (客户端) 包括:

1. Create a socket

2. Connect to remote server

3. Send some data

4. Receive a reply

server 端:

1. Open a socket

2. Bind to a address and port

3. Listen for incoming connections

4. Accept connections

4. Read / Send

常用套接字方法

  • bind() 方法绑定一个 socket, 例如
  • # Bind the socket to the port
    server_address = ('localhost', 10000)
    sock.bind(server_address)

     

  • listen() 方法监听端口

  • accept() 方法等待 incoming connection, accept() 方法返回 an open connection 和 client address, the connection 实际是一个不同的在另外的端口 (由内核分配) 上的 socket, 接收数据是 conn.recv(), 发送是 conn.sendall(). The return value of accept() is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.

  • # Listen for incoming connections
    sock.listen(1)
    
    while True:
        # Wait for a connection
        connection, client_address = sock.accept()
        try:
            # Receive the data in small chunks and retransmit it
            while True:
                # recv data 
                data = connection.recv(16)
                if data:
                    # send data back
                    connection.sendall(data)
                else:
                    break
        finally:
            # Clean up the connection
            connection.close()

     

 

posted @ 2016-07-09 11:17  garyyang  阅读(178)  评论(0)    收藏  举报