python基礎-day33__python

來源:互聯網
上載者:User
#TCP,Server端代碼,import socket'''首先匯入socke模組'''sk = socket.socket()'''建立一個socket對象,def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None):預設參數的意思是,family=AF_INET,協議族預設ipv4,type=SOCK_STREAM,預設是TCP的,後面兩個暫時沒有涉及'''sk.bind(('127.0.0.1',9999))'''我們通過通訊端這個服務,綁定到我們本地的一個地址,(ip,port)作為伺服器,你需要設定自己的資訊,好讓別人知道如何串連你,    def bind(self, address): # real signature unknown; restored from __doc__              Bind the socket to a local address.'''sk.listen()                          #等待別人來串連你'''    def listen(self, backlog=None): # real signature unknown; restored from __doc__        Enable a server to accept connections.          backlog=None,目前沒涉及,不過應該是關於串連數的吧?'''conn,addr = sk.accept()'''此函數會在這裡停滯,等待別人串連,如果串連成功,會返回串連方的資訊,    def accept(self):        accept() -> (socket object, address info)        Wait for an incoming connection.  Return a new socket        representing the connection, and the address of the client.        For IP sockets, the address info is a pair (hostaddr, port).        等待來到的串連,返回一個(新的通訊端,地址資訊)代表新的串連,'''print(addr)conn.send('你好'.encode('utf-8'))'''發送字串形式的資料,返回傳送的位元組數,    def send(self, data, flags=None): # real signature unknown; restored from __doc__        send(data[, flags]) -> count        Send a data string to the socket.  For the optional flags        argument, see the Unix manual.  Return the number of bytes        sent; this may be less than len(data) if the network is busy.'''ret = conn.recv(1024)   #1024  表示接受1024個位元組'''    def recv(self, buffersize, flags=None): # real signature unknown; restored from __doc__        recv(buffersize[, flags]) -> data'''print(ret.decode('utf-8'))conn.close()   # 掛電話sk.close()     # 關手機'''這裡i的兩個通訊端,分別代表,1.伺服器用於監聽的通訊端,2.建立立串連的通訊端,都需要我們關閉    def close(self):        # This function should not reference any globals. See issue #808164.        self._closed = True        if self._io_refs <= 0:      #一個通訊端可能涉及多個遠方多個資料的收發,所以要判斷還有其它串連,            self._real_close()'''



#TCP,Client端代碼import socketsk = socket.socket()sk.connect(('127.0.0.1',9999))'''    def connect(self, address): # real signature unknown; restored from __doc__        connect(address)'''ret = sk.recv(1024)print(ret.decode('utf-8'))sk.send('你也好'.encode('utf-8'))sk.close()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.