Python--網路編程-----socket代碼執行個體--聊天軟體升級版

來源:互聯網
上載者:User

標籤:set   ror   error   ted   bin   list   decode   span   升級版   

服務端代碼:

 1 import socket 2  3 HOST = ‘‘ 4 PORT = 50007 5  6 sock_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 sock_server.bind((HOST, PORT)) 8  9 sock_server.listen(1)10 11 while True:12     conn, addr = sock_server.accept()13 14     with conn:15         print(‘Connected by‘, addr)16         while True:17             try:18                 data = conn.recv(1024)19                 print("server recv:", conn.getpeername(), data.decode())20                 if not data:21                     break22 23                 conn.send(data.upper())24                 print("send to alex:", data)25             except ConnectionResetError:26                 break

用戶端1代碼:

import socketHOST = ‘localhost‘PORT = 50007client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)client.connect((HOST, PORT))while True:    msg = input(">>>:").strip()    if len(msg) == 0:        continue    client.sendall(msg.encode())    data = client.recv(1024)    print(‘Received‘, data.decode())

用戶端2代碼:

 1 import socket 2  3 HOST = ‘localhost‘ 4 PORT = 50007 5  6 client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 7 client.connect((HOST, PORT)) 8  9 while True:10     msg = input(">>>:").strip()11     if len(msg) == 0:12         continue13     client.sendall(msg.encode())14 15     data = client.recv(1024)16 17     print(‘Received‘, data.decode())

先開啟服務端,然後開啟用戶端1,用戶端2,在用戶端1輸入資訊能夠收到服務端的響應資訊,在用戶端2輸入資訊不能收到服務端的響應資訊,此時斷開用戶端1 的串連,用戶端2可以正常收到服務端的響應資訊,

用戶端1運行結果:

1 >>>:用戶端12 Received 用戶端13 >>>:4 Process finished with exit code 1

用戶端2運行結果:

1 >>>:用戶端22 Received 用戶端23 >>>:

服務端運行結果:

1 Connected by (‘127.0.0.1‘, 58852)2 server recv: (‘127.0.0.1‘, 58852) 用戶端13 send to alex: b‘\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf1‘4 Connected by (‘127.0.0.1‘, 58857)5 server recv: (‘127.0.0.1‘, 58857) 用戶端26 send to alex: b‘\xe5\xae\xa2\xe6\x88\xb7\xe7\xab\xaf2‘

 

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.