python socket 基本使用

來源:互聯網
上載者:User

標籤:基本使用   cli   cte   send   服務   imp   客戶   ESS   class   

socket通常也叫做“通訊端”,用於串連server client,是一個通訊鏈的控制代碼,應用程式通常通過通訊端向網路發出請求或應答網路請求。

就像python 處理file一樣:

file是針對某個檔案 開啟-->讀寫-->關閉

socket是針對伺服器 用戶端進行 開啟-->讀寫-->關閉

server部分:

import socket,sysserver_address=(‘127.0.0.1‘, 8000)BUF_SIZE=1024try:   server_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)     #建立新的socket對象except socket.error, msg:   print "socket create fail, error code:" + str(msg[0]) + ‘error message:‘ + msg[1]print ‘socket create successfully‘try:   server_sk.bind(server_address)                                   #綁定server地址,address取決於地址族,AF_INET以元組表示except socket.error, msg:   print "socket bind address error:" + str(msg[0]) + ‘error mssage:‘ + msg[1]print ‘socket bind address successfully‘server_sk.listen(5)print "listening..."while True:   client_sk, client_addr = server_sk.accept()   print "connected by:", client_addr   while True:      data=client_sk.recv(BUF_SIZE)      print data      client_sk.sendall(data)server_sk.close()
參數一:地址簇socket.AF_INET IPv4(預設)socket.AF_INET6 IPv6
參數二:類型socket.SOCK_STREAM  流式socket , for TCP (預設)socket.SOCK_DGRAM   資料報式socket , for UDP
Client部分:
import socket,sysserver_address=(‘127.0.0.1‘, 8000)BUF_SIZE=1024try:   client_sk=socket.socket(socket.AF_INET, socket.SOCK_STREAM)except socket.error, msg:   print "socket create fail, error code:" + str(msg[0]) + ‘error message:‘ + msg[1]client_sk.connect(server_address)while True:   data= raw_input(‘please input your sending message->‘)   if not data:      print "input data cannot be empty, please input again.."      continue   client_sk.sendall(data)   recv_data = client_sk.recv(BUF_SIZE)   print recv_dataclient_sk.close()

server 輸出:

socket create successfully
socket bind address successfully
listening...
connected by: (‘127.0.0.1‘, 63388)
aa

client 輸出:

please input your sending message->aa
aa
please input your sending message->

python socket 基本使用

相關文章

聯繫我們

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