Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Select of connections
#1
Hello there.
I'd like to get some help to understand the basics of socket's work

The conditions are next:
1) server keeps 2 client connections maximum
2) when client connects to server, he's getting some ID
3) I can send some message directly to the client with some ID
4) client can send some message to the server

I need help to realize these conditions.

My server's code:

import socket as skt
import pymysql as pms
from pymysql.cursors import DictCursor as Dc
from contextlib import closing as cls

IP = "127.0.0.1"
PORT = 9876

server_socket = skt.socket(skt.AF_INET, skt.SOCK_STREAM)
server_socket.setblocking(False)
server_socket.setsockopt(skt.SOL_SOCKET, skt.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen(2)

print("Listening for connections on {}:{}".format(IP, PORT))

while True:
    conn, addr = server_socket.accept()

    message = conn.recv(1024)
    message = message.decode()
    logindata = message.split(",")

    username = logindata[0]
    password = logindata[1]

    print(username, password)

    with cls(pms.connect(
        host='localhost',
        user='adam',
        password='password',
        db='test',
        charset='utf8mb4',
        cursorclass=Dc
    )) as dbconn:
        with dbconn.cursor() as cursor:
            query = "SELECT * FROM test.users WHERE username = '{}' and password = '{}'".format(username, password)
            cursor.execute(query)
            for row in cursor:
                print(row)

My client's code:
import tkinter as tk
import pymysql as pms
import socket as skt
import select as sel


class AuthWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.geometry("320x240")
        self.resizable(False, False)

        # USERNAME
        self.ul = UsernameLabel(self, text="Username:") # 59 x 21
        self.ue = UsernameEntry(self) # 19

        # PASSWORD
        self.pl = PasswordLabel(self, text="Password:")
        self.pe = PasswordEntry(self)

        self.cb = ConnectButton(self, text="Connect", command=self.connect)

    def connect(self):
        username = self.ue.get()
        password = self.pe.get()

        # print(username, password)

        IP = "127.0.0.1"
        PORT = 9876

        client_socket = skt.socket(skt.AF_INET, skt.SOCK_STREAM)
        client_socket.connect((IP, PORT))
        client_socket.setblocking(False)

        message = "{},{}".format(username, password).encode('utf-8')
        print(message)

        client_socket.sendall(message)


class UsernameLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place(x=15, y=15)


class UsernameEntry(tk.Entry):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place(x=80, y=17, )


class PasswordLabel(tk.Label):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place(x=15, y= 40)


class PasswordEntry(tk.Entry):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place(x=80, y=40)


class ConnectButton(tk.Button):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.place(x=60, y=70)

Thanks in advance for help!
Quote
#2
I've tried to change my server socket's code to something like this...
import socket as skt
import select as sel

IP = "127.0.0.1"
PORT = 9876

server_socket = skt.socket(skt.AF_INET, skt.SOCK_STREAM)
server_socket.setsockopt(skt.SOL_SOCKET, skt.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
server_socket.listen()

sockets_list = [server_socket]
clients = {}

print("Listening for connections on {}:{}".format(IP, PORT))


def receive_message(client_socket):
    try:
        message = client_socket.recv(1024)

        if not len(message):
            print("FALSE!")
            return False

        #return message.decode("utf-8")
        print(message.decode())
        return message.decode()

    except:
        return False


while True:
    read_sockets, _, exception_sockets = sel.select(sockets_list, {}, sockets_list)

    for notified_socket in read_sockets:
        #print(notified_socket)
        if notified_socket == server_socket:
            client_socket, client_address = server_socket.accept()
            message = receive_message(client_socket)
            print("Pre-Connected!")
            if message is False:
                continue
            sockets_list.append(client_socket)
            print("Connected!")

        else:
            message = receive_message(notified_socket)

            if message is False:
                print('Connection is closed...')
                sockets_list.remove(notified_socket)
                continue

            print(message + "123")

    for notified_socket in exception_sockets:
        sockets_list.remove(notified_socket)
But when server receives the message, it's automatically receives one more empty message, which makes connection shut down. How can I fix that?
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Asyncio select.select Mradr 3 1,121 Aug-12-2018, 02:56 PM
Last Post: Larz60+
  Aggregate multiple telnet connections Jibeji 1 1,754 Mar-02-2018, 07:21 PM
Last Post: mpd

Forum Jump:


Users browsing this thread: 1 Guest(s)