Python,客户端 - 服务器应用程序,无法连接

时间:2017-11-06 19:02:18

标签: python python-3.x asynchronous server client

由于某种原因,下一个基本程序仅在第二次将客户端连接到服务器。所以每次重启服务器后都是如此。有人可以解释这种行为的原因以及如何解决这个问题?也许是因为asyncore只在服务器端使用? (Windows 7,Python 3)提前感谢您!

Сlient:

import socket
sock = socket.socket()
host = 'localhost'
port = 8081
tempr = port
sock.connect((host,port))

服务器:

import asyncore 
import socket 
import time

class EchoHandler(asyncore.dispatcher_with_send):

def handle_read(self):
  data = self.recv(1024)

class EchoServer(asyncore.dispatcher):
  def __init__(self, host, port):
  asyncore.dispatcher.__init__(self)
  self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
  self.set_reuse_addr()
  self.bind((host, port))
  self.listen(2)

  def handle_accept(self):
    pair = self.accept()
    if pair is not None:
      sock, addr = pair
      print ('Incoming connection from %s' % repr(addr))
      handler = EchoHandler(sock)

def main():
  host = 'localhost'
  port = 8081
  server = EchoServer(host, port)

  print ('Server %s running'% port)
  asyncore.loop()

if __name__ == '__main__': 
   main()

1 个答案:

答案 0 :(得分:0)

socket的重点是客户端和服务器之间的send()recv()(接收)数据。在连接到服务器之后,您必须向服务器发送一些数据(甚至必须发送空字符串),服务器可能会将一些数据返回给客户端和/或只是关闭连接。

my_client.py

import socket

sock = socket.socket()
sock.connect(('localhost', 8081))
sock.send(b'data from client')
print(sock.recv(32))
sock.close()

my_server.py

import asyncore
import socket
import time


class EchoHandler(asyncore.dispatcher_with_send):
    def handle_read(self):
        data = self.recv(1024)
        print('data from client', data)
        self.send(b'data from server')
        self.close()


class EchoServer(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(2)

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            print('Incoming connection from %s' % repr(addr))
            handler = EchoHandler(sock)


def main():
    host = 'localhost'
    port = 8081
    server = EchoServer(host, port)

    print('Server %s running' % port)
    asyncore.loop()


if __name__ == '__main__':
    main()

<强>更新
您确实收到错误:OSError: [WinError 10038],因为您正在关闭服务器中的套接字而不从客户端读取所有数据。客户方也是这样。
在Python文档中,明确声明这些是very basic示例。

使用方法sendall()确保发送所有数据。方法send()无法保证发送所有数据。

您必须使用while循环从套接字读取数据:

my_client.py

import socket

sock = socket.socket()
sock.connect(('localhost', 8081))
sock.sendall(b'data from client')

chunk = b''  # socket.recv returns bytes
data = b''  # defined before to avoid NameError 
while True:
    chunk = sock.recv(32)
    if chunk:
        data += chunk
    else:
        break

print(data)
sock.close()

my_server.py

import asyncore
import socket
import time


class EchoHandler(asyncore.dispatcher_with_send):
    def handle_read(self):

        chunk = b''  # socket.recv returns bytes
        data = b''  # defined before to avoid NameError
        while True:
            chunk = self.recv(1024)
            if chunk:
                data += chunk
            else:
                break

        print('data from client', data)
        self.sendall(b'data from server')
        self.close()


class EchoServer(asyncore.dispatcher):
    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(2)

    def handle_accept(self):
        pair = self.accept()
        if pair is not None:
            sock, addr = pair
            print('Incoming connection from %s' % repr(addr))
            handler = EchoHandler(sock)


def main():
    host = 'localhost'
    port = 8081
    server = EchoServer(host, port)

    print('Server %s running' % port)
    asyncore.loop()


if __name__ == '__main__':
    main()