简体   繁体   中英

Multiple socket threads on same computer

I am learning multithreading and sockets on Python but I came across a problem. I am trying to create a server which would receive and print data from multiple clients on the same computer. Here is my server code so far:

import socket
import threading

def conn(HOST, PORT, BUFSIZE):
    serversock = RecvConnection(HOST, PORT) 
    serversock.listen(BUFSIZE)

class RecvConnection(object):

    def __init__(self,host, port, sock=None):
        if sock == None:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

        self.sock.bind((host, port))    

    def listen(self, buffsize):
        self.sock.listen(5)
        clisock, (remhost, remport) = self.sock.accept()
        while 1:
            print clisock.recv(buffsize)

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024


threading.Thread(target=conn, args=(HOST, PORT, BUFSIZ,)).start()

The problem is that only one instance of my client file seems to be treated by my server, so it shows only the data sent by the 1st instance of my client. Here is my client code:

import socket
import threading

class CreateConnection(object):

    def __init__(self, sock=None):
        if sock is None:
            # Create a socket
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        else:
            self.sock = sock

    def connect(self, host, port):
        # Connect to host, port
            self.sock.connect((host, port))

class Communication(CreateConnection):

    def sendMsg(self, msg):
        self.sock.send(msg)

HOST = 'localhost'
PORT = 21567

cltsock = Communication()
cltsock.connect(HOST, PORT)
while 1:
    msg = raw_input('> ')
    cltsock.sendMsg(msg)

Anyone could help me to make this happen ? Thanks !

When the server accepts a connection from a client, it should start a thread to handle that connection and then loop around to wait for the next client.

[edit]

Here's an example of what I mean:

def listen(self, buffsize):
    self.sock.listen(5)

    while True:
        # Listen for a new client.
        clisock, (remhost, remport) = self.sock.accept()

        # Start listening to the new client.
        t = threading.Thread(target=self._handle_client, args=(clisock, buffsize))
        t.start()

def _handle_client(self, clisock, buffsize):
    while True:
        received = clisock.recv(buffsize)
        if not received:
            # The client has closed the connection.
            break

        print received

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM