0

チャットプログラムを作っています。取得するすべての接続要求に対して新しいスレッドを作成する (TCP) サーバーがあります。

  1. クライアントが接続を終了/終了するときに問題が発生します。サーバーはエラーを発生させます(以下)。どうすればそれを処理できますか?
  2. また、サーバーは、あるクライアントから受け取った「データ」を別の (変更可能な) クライアントに送信する必要があります。
    これを実装するにはどうすればよいですか??

クライアントが終了すると、次のエラーが表示されます。

Exception in thread Thread-1:
    Traceback (most recent call last):
      File "C:\Python2.7 For Chintoo\lib\threading.py", line 552, in __bootstrap_inner
        self.run()
      File "C:\Python2.7 For Chintoo\lib\threading.py", line 505, in run
        self.__target(*self.__args, **self.__kwargs)
      File "C:\Users\karuna\Desktop\Jython\Python\My Modules\Network\Multi-server.py", line 23, in recv_loop
        data = client.recv(1024)
    error: [Errno 10054] An existing connection was forcibly closed by the remote host

私のスクリプト:

マルチサーバー.py

import os, socket, time, threading, random

class Server:
    def __init__(self,host,port,user):
        self.port = port
        self.host = host
        self.user = user
        self.bufsize = 1024
        self.addr = (host,port)

        self.socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM)
        self.socket.bind(self.addr)
        print "Server running on",host,"at port",port

        self.socket.listen(5)

def recv_loop(server,client,caddr):
    print 'Connected To',caddr

    while True:
        global clients
        name = clients[client]
        data = client.recv(1024)
        if not data:
            break
        print name + " said: " + data
    client.close()


host = 'localhost'
port = random.randint(1025,60000)
user = 'No one'

server = Server(host, port, user)

clients = {}
threads = []
while True:
    client, caddr = server.socket.accept()
    # name extraction
    name = client.recv(1024)

    clients[client] = name

    thread = threading.Thread(target=recv_loop, args=(server,client, caddr))
    thread.start()

client.py

from socket import *

host = 'localhost'
name = raw_input('Enter name: ')
port = int(raw_input('Enter server port: '))
bufsiz = 1024
addr = (host, port)

tcpClient = socket(AF_INET , SOCK_STREAM)
tcpClient.connect(addr)

# sending name
tcpClient.send(name)

while True:
    data = raw_input('> ')
    if not data:
        break
    tcpClient.send(data)
raw_input('Enter to Quit')
4

2 に答える 2

0

Python でソケット プログラミングを行ったことはありませんが、クライアントが終了する前にソケット接続をきれいに閉じたいと思うかもしれません。closeクライアントでメソッドを使用します。

于 2013-02-17T04:43:23.750 に答える
0

問題1

クライアント側でソケット接続を閉じるだけです:

raw_input('Enter to Quit')
tcpClient.close()

問題 2

ここで生産者と消費者の問題を見ています。

基本的な解決策:

受信ループは を取得しthreading.Condition、グローバル配列を更新して を呼び出す必要がありますnotifyAll。送信ループは を取得しcondition、配列からデータを読み取り、クライアントに送信する必要があります。

于 2013-02-17T04:55:21.720 に答える