Python의 소켓에 대한 자세한 소개

零下一度
풀어 주다: 2017-07-18 15:23:35
원래의
2097명이 탐색했습니다.

소켓은 종종 "소켓"이라고 불리며, IP 주소와 포트를 설명하는 데 사용됩니다. 애플리케이션은 일반적으로 "소켓"을 통해 네트워크에 요청하거나 네트워크 요청에 응답합니다.

Socket은 Unix에서 유래되었으며 Unix/Linux의 기본 철학 중 하나는 "모든 것이 파일이다"입니다. 파일을 조작하려면 [열기] [읽기-쓰기] [닫기] 모드를 사용하세요. 소켓은 이 모드의 구현입니다. 소켓은 특수 파일이며 일부 소켓 기능은 이에 대한 작업입니다(읽기/쓰기 IO, 열기, 닫기).

소켓과 파일의 차이점:

파일 모듈 1. 소켓 모듈

  소켓은 실제로는 IP 주소와 포트의 조합입니다. 이 형식(ip, port)과 유사합니다. 여기서 ip는 특정 호스트를 나타내고 port는 애플리케이션을 나타냅니다. 소켓을 통해 다른 호스트와 통신할 수 있습니다.

  소켓 소스코드 분석은 현재 작성중인 tarnado 시리즈 기사에 있습니다. . . . .

  1. 통신 방식

  tcp 통신

  udp 통신

  Unix 기반 통신

2. 소켓 방식

# 暂时知道的也就这么多,之后要是在用到其他的我会继续进行保存Methods of socket objects (keyword arguments not allowed):
    
    _accept() -- accept connection, returning new socket fd and client address
    bind(addr) -- bind the socket to a local address 给本地地址绑定一个socket套接字
    close() -- close the socket 关闭一个套接字
    connect(addr) -- connect the socket to a remote address     连接到远端主机
    connect_ex(addr) -- connect, return an error code instead of an exception
    dup() -- return a new socket fd duplicated from fileno()
    fileno() -- return underlying file descriptor
    getpeername() -- return remote address [*]
    getsockname() -- return local address
    getsockopt(level, optname[, buflen]) -- get socket options
    gettimeout() -- return timeout or None
    listen([n]) -- start listening for incoming connections
    recv(buflen[, flags]) -- receive data   接受数据
    recv_into(buffer[, nbytes[, flags]]) -- receive data (into a buffer)    接受数据到缓冲区中,
    recvfrom(buflen[, flags]) -- receive data and sender's address    recvfrom_into(buffer[, nbytes, [, flags])      -- receive data and sender's address (into a buffer)sendall(data[, flags]) -- send all data 发送数据给远端主机,3.x之后只能发送字节形式,因此在发送的时候一般要进行转换bytes
    send(data[, flags]) -- send data, may not send all of it 也是发送数据,区别在于send发送的不完整,随机进行发送的,二sendall发送的完整
    sendto(data[, flags], addr) -- send data to a given address 基于udp发送数据的
    setblocking(0 | 1) -- set or clear the blocking I/O flag    是否设置成阻塞模式0 代表阻塞,1代表非阻塞
    setsockopt(level, optname, value) -- set socket options     设置一些socket的桉树
    settimeout(None | float) -- set or clear the timeout    设置超时市场
    shutdown(how) -- shut down traffic in one or both directions    
    if_nameindex() -- return all network interface indices and names
    if_nametoindex(name) -- return the corresponding interface index
    if_indextoname(index) -- return the corresponding interface name
 
     [*] not available on all platforms!
로그인 후 복사

2. 단순 채팅 로봇
한 개 보내면 데이터가 있으면 서버가 응답합니다. 데이터 + Hello

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/3 4  5 import socket 6 # 创建一个server对象 7 server_obj = socket.socket() 8 # 绑定一下端口 9 server_obj.bind(("127.0.0.1", 8888, ))10 # 设置监听的等待队列长度为5,当大于5的时候就拒绝连接11 server_obj.listen(5)12 13 while True:14     # 等待接受客户端的连接,为阻塞方式15     conn, address = server_obj.accept()16     # 发送欢迎信息17     conn.sendall(bytes("欢迎来到简单的聊天室..", encoding='utf-8'))18     while True:19         # 接受到对面的消息就会把对面消息后面加上你好重新发送回去20         ret = str(conn.recv(1024), encoding='utf-8')21         if ret == 'q':22             # 如果对面发送的为q就退出23             break24         conn.sendall(bytes(ret + ",你好", encoding='utf-8'))
로그인 후 복사
server
# -*- coding:utf-8 -*-# zhou# 2017/7/3import socket

client = socket.socket()
client.connect(("127.0.0.1", 8888, ))# 接受欢迎信息并打印ret = str(client.recv(1024), encoding='utf-8')print(ret)while True:
    message = input("请输入您要发送的内容:")
    client.sendall(bytes(message, encoding='utf-8'))if message == 'q':breakret = str(client.recv(1024), encoding='utf-8')print(ret)
로그인 후 복사
client
3. 간단한 FTP 업로드

서버에 업로드

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5 import socket 6  7 server = socket.socket() 8 server.bind(("127.0.0.1", 9998, ))  # 绑定ip 9 server.listen(5)10 11 while True:12     conn, address = server.accept()13     # 连接之后首先接收文件大小14     file_size = int(str(conn.recv(1024), encoding='utf-8'))15     # 用来解决粘包问题的16     conn.sendall(bytes("1001", encoding='utf-8'))17     # 已经接受的文件大小18     has_size = 019     num = 120     # 连接之后接收文件21     f = open("new.jpg", 'wb')22     while True:23         num += 124         if file_size == has_size:25             break26         data = conn.recv(1024)27         f.write(data)28         has_size += len(data)29     f.close()   # 关闭文件
로그인 후 복사
ftpserver

 1 # -*- coding:utf-8 -*- 2 # zhou 3 # 2017/7/2 4  5  6 import os 7 import socket 8  9 client = socket.socket()10 11 client.connect(("127.0.0.1", 9998), )12 # 传送文件大小13 file_size = os.stat("1.jpg").st_size14 print(file_size)15 # 发送文件大小16 client.sendall(bytes(str(file_size), encoding='utf-8'))17 client.recv(1024)   # 解决粘包问题18 # 发送文件19 with open("1.jpg", 'rb') as f:20     for line in f:21         client.sendall(line)22 client.close()
로그인 후 복사
ftpclient
Four. 해결 방법

FTP 업로드 프로세스 설명,

  문제는 파일을 업로드할 때 파일을 먼저 업로드한다는 것입니다. 사이즈를 업로드한 후 승인서를 작성해야 하며, 서버측에서는 파일 사이즈를 받은 후 즉시 확인용 데이터를 보내야 크기별로 데이터를 완벽하게 구분할 수 있습니다.

 

위 내용은 Python의 소켓에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!