Python之路——網路編程

來源:互聯網
上載者:User

標籤:rom   enc   用戶端   repr   span   ble   res   blog   color   

socketTCP服務端
 1 import socket 2 sk = socket.socket() 3 sk.bind((‘127.0.0.1‘,8080)) # 綁定ip和連接埠號碼 4 sk.listen() # Enable a server to accept connections. 5 conn,addr = sk.accept() # Wait for an incoming connection.  Return a new socket 6                         # representing the connection, and the address of the client. 7 while 1: 8     content = conn.recv(1024)   # 接收 9     print(content.decode(‘utf-8‘))10     conn.send(content+b‘--liuyankui‘)   # 發送11 conn.close()12 sk.close()
用戶端
1 import socket2 sk = socket.socket()3 sk.connect((‘127.0.0.1‘,8080))  #串連4 while 1:5     content = input(‘>>>‘).encode(‘utf-8‘)6     sk.send(content)7     ret = sk.recv(1024)8     print(ret.decode(‘utf-8‘))9 sk.close()

 

UDP服務端
1 import socket2 sk = socket.socket(type=socket.SOCK_DGRAM)3 sk.bind((‘127.0.0.1‘,8080))4 msg ,addr = sk.recvfrom(1024)5 print(msg.decode(‘utf-8‘))6 sk.sendto(b‘bye‘,addr)7 sk.close()
使用者端
1 import socket2 sk = socket.socket(type=socket.SOCK_DGRAM)3 ip_port = (‘127.0.0.1‘,8080)4 sk.sendto(b‘hello‘,ip_port)5 msg,addr = sk.recvfrom(1024)6 print(msg.decode(‘utf-8‘))7 sk.close()

 

Python之路——網路編程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.