如何关闭所有线程并终止连接

时间:2019-04-04 20:05:14

标签: python multithreading networking

我正在尝试实现此处编写的代码:

https://www.geeksforgeeks.org/simple-chat-room-using-python/

我可以使其正常运行,但找不到关闭连接的方法。该代码一直运行到我输入键盘中​​断为止。我想实现一个关键字,它将关闭客户端和服务器并释放端口。

我已经实现了客户端代码,以在消息“退出”时退出,但是相同的技术在服务器代码中不起作用。我一直被“ conn,addr = server.accept()”这一行所吸引,并返回错误

Traceback (most recent call last):
  File "newServer.py", line 66, in <module>
    conn, addr = server.accept()
  File "/Users/######/anaconda3/lib/python3.7/socket.py", line 212, in accept
    fd, addr = self._accept()
ConnectionAbortedError: [Errno 53] Software caused connection abort

任何帮助将不胜感激!

编辑:添加代码

server.py:

import socket
import select
from _thread import *
import threading
import sys


server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
"""
the first argument AF_INET is the address domain of the socket. This is used when we have an Internet Domain
with any two hosts
The second argument is the type of socket. SOCK_STREAM means that data or characters are read in a continuous flow
"""
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

IP_address = "127.0.0.1"
Port = 12230

server.bind((IP_address, Port)) 
#binds the server to an entered IP address and at the specified port number. The client must be aware of these parameters
server.listen(100)
#listens for 100 active connections. This number can be increased as per convenience
list_of_clients=[]

def clientthread(conn, addr):
    conn.send("Welcome to this chatroom!".encode())
    #sends a message to the client whose user object is conn
    while True:
            try:     
                message = conn.recv(2048).decode()
                if message:
                    print ("<" + addr[0] + "> " + message)
                    message_to_send = "<" + addr[0] + "> " + message
                    broadcast(message_to_send,conn)
                    #prints the message and address of the user who just sent the message on the server terminal
                else:
                    remove(conn)
            except:
                continue

def broadcast(message,connection):
    for clients in list_of_clients:
        if clients!=connection:
            try:
                clients.send(message.encode())
            except:
                clients.close()
                remove(clients)

def remove(connection):
    if connection in list_of_clients:
        list_of_clients.remove(connection)

while True:
    conn, addr = server.accept()
    """
    Accepts a connection request and stores two parameters, conn which is a socket object for that user, and addr which contains
    the IP address of the client that just connected
    """
    list_of_clients.append(conn)
    print (addr[0] + " connected")
    #maintains a list of clients for ease of broadcasting a message to all available people in the chatroom
    #Prints the address of the person who just connected
    start_new_thread(clientthread,(conn,addr))
    #creates and individual thread for every user that connects

conn.close()
server.close()

client.py

import socket 
import select 
import sys 

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

IP_address = "127.0.0.1"
Port = 12230

server.connect((IP_address, Port)) 

while True: 

    # maintains a list of possible input streams 
    sockets_list = [sys.stdin, server] 

    """ There are two possible input situations. Either the 
    user wants to give  manual input to send to other people, 
    or the server is sending a message  to be printed on the 
    screen. Select returns from sockets_list, the stream that 
    is reader for input. So for example, if the server wants 
    to send a message, then the if condition will hold true 
    below.If the user wants to send a message, the else 
    condition will evaluate as true"""
    read_sockets,write_socket, error_socket = select.select(sockets_list,[],[]) 

    for socks in read_sockets: 
        if socks == server: 
            message = socks.recv(2048).decode()
            print (message)
        else: 
            message = input("Message: ")
            server.send(message.encode()) 
            print("<You>") 
            print(message) 
server.close() 

0 个答案:

没有答案