亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

簡單的 Python 套接字服務器不能在 macOS 上運行

簡單的 Python 套接字服務器不能在 macOS 上運行

墨色風雨 2023-02-22 13:54:28
我創建了一個小的 Python 套接字服務器代碼,當我嘗試連接客戶端時,我得到:OSError: [Errno 57] Socket is not connected我不確定為什么我得到它,即使服務器正在運行。這是我的代碼: server.py# Importsimport socket# Variablesip_address = ''ip_port = 10000max_connections = 5txt = 'utf-8's = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# Codes.bind((socket.gethostname(), ip_port))s.listen(max_connections)while True:    clientsocket, address = s.accept()    print(f"{address} connected!")    clientsocket.send(bytes("quit", txt))client.py# Importsimport socket# Variablesip_address = ''ip_port = 10000txt = 'utf-8's = socket.socket(socket.AF_INET, socket.SOCK_STREAM)msg = s.recv(1024)# Code"""Connect to the server"""s.connect((ip_address, ip_port))while True:    var = msg.decode(txt)    print(var)    if var == "quit":        break
查看完整描述

1 回答

?
隔江千里

TA貢獻1906條經驗 獲得超10個贊

我已經更改了您的代碼中的一些點,它在這里工作正常。我已經將 ip_address 設置為 127.0.0.1 擔心 MacOS 的安全問題。我還刪除了發送函數的第二個參數。


server.py


# Imports

import socket


# Variables

ip_address = '127.0.0.1'

ip_port = 10000

max_connections = 5


txt = 'utf-8'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# Code

s.bind((ip_address, ip_port))

s.listen(max_connections)


while True:

    clientsocket, address = s.accept()

    print("{} connected!", address)

    clientsocket.send(b"quit")

在客戶端,在套接字連接之前調用 recv。


client.py


# Imports

import socket


# Variables

ip_address = '127.0.0.1'

ip_port = 10000


txt = 'utf-8'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# Code

"""Connect to the server"""

s.connect((ip_address, ip_port))


while True:

    msg = s.recv(1024)

    var = msg.decode(txt)

    if var == "quit":

        break


查看完整回答
反對 回復 2023-02-22
  • 1 回答
  • 0 關注
  • 224 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號