Python - 由于套接字未连接,发送或接收数据的请求被禁止

Lin*_*ink 3 python sockets

我正在 Pygame 中创建一个游戏,需要多人游戏的客户端服务器部分。

首先,我检查连接是否少于两个。如果是这种情况,客户端将看到一个屏幕,显示“正在等待连接”。

我已经让客户端成功向服务器发送“1”消息,如果服务器未满,服务器将响应“1”。因此,如果服务器未响应 1,则服务器已满,客户端可以继续。

但是,我收到标题中提到的此错误。

服务器代码:

import socket
import sys
import threading
from _thread import *
import time

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

host=socket.gethostname()
ip=socket.gethostbyname(host)
port=8000

connections=[]

print('Your local ip address is',ip)

s.bind((host,port))
s.listen(2)

def  threaded_client(connection):

    while True:
        data=connection.recv(2048) #anything we receive
        if not data:
            break

    connection.close()


def checkconnected(connections):
    noofconn=len(connections)



while True:

    print('Waiting for a connection...')
    connection,address=s.accept()
    print(address,'has connected to server hosted at port',address[1])
    connections.append(address)



    data=connection.recv(1024)

    received=[]
    counter=0

    for letter in data:
        received.append(data[counter])
        counter+=1

    received=(chr(received[0]))     

    if received=='1':#handling initial connections
        if len(connections)!=2:
            s.sendall(b'1')

    if not data:
        break


    start_new_thread(threaded_client,(connection,))


s.close()
Run Code Online (Sandbox Code Playgroud)

调用它的客户端代码:

host=socket.gethostname()
            ip=socket.gethostbyname(host)
            s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            address=address
            port=8000

            if address==ip:
                ishost=True

            else:
                ishost=False

            try:
                s.connect((address,port))
                connectionwaitingmenu()
                connected=False

                while connected==False:
                    s.sendall(b'1')
                    data=s.recv(1024)
                    received=[]
                    counter=0

                    for letter in data:
                        received.append(data[counter])
                        counter+=1

                    received=(chr(received[0])) 

                    if received=='1':
                        connected=False
                    elif received!='1':
                        connected=True
                        classselection()
Run Code Online (Sandbox Code Playgroud)

该错误发生在服务器代码中的 s.sendall(b'1') 行上。

bna*_*ker 5

您的代码中还有一些其他问题,但标题中错误的原因是您使用了错误的套接字在服务器端发送和接收数据。

当服务器接受一个新的客户端 ( conn, addr = server.accept()) 时,它会返回一个新的套接字,它代表您与客户端通信的通道。与该客户的所有进一步沟通都是通过在 上进行阅读和写作来进行的conn。您不应该调用recv()or sendall()on s,这是服务器套接字。

代码应该如下所示:

# Assuming server is a bound/listening socket
conn, addr = server.accept()

# Send to client
conn.sendall(b'hello client')

# Receive from client
response = conn.recv(1024)

# NO
server.send(b'I am not connected')
this_wont_work = server.recv(1024)
Run Code Online (Sandbox Code Playgroud)