Presentation is loading. Please wait.

Presentation is loading. Please wait.

INTRO2CS Tirgul 12 – Networks and GUI. Today:  Network and Communication  GUI - tkinter.

Similar presentations


Presentation on theme: "INTRO2CS Tirgul 12 – Networks and GUI. Today:  Network and Communication  GUI - tkinter."— Presentation transcript:

1 INTRO2CS Tirgul 12 – Networks and GUI

2 Today:  Network and Communication  GUI - tkinter

3 Network  A computer network is a network which allows computers to exchange data  Networked computing devices exchange data with each other along data connections  The connections between computers are established using either cable media or wireless media.

4 Client-Server Model

5  It is a network architecture in which each computer or process on the network is either a client or a server.  The server component provides a function or service to one or many clients  For instance, a web server serves web pages and a file server serves computer files.

6 Client-Server Model  The client component request services from the server  For example, web browsers are clients that connect to web servers and retrieve web pages for display.

7 Server-Client Model Usage Examples  Email  Printers  Internet  Atually, many of the application we use daily:  Whats up  Facebook  Waze  Dropbox

8 Who can be a client? Server?  We are used to talk about servers (“ooh, Google servers are so strong!”) as a synonym for a powerful computer.  But, being a client or a server is just a role a specific program takes on itself.  We can run several program on the same machine :  Some would be clients that will reach other servers for service.  Some would be servers providing services to other clients, or even to a client on the current machine.

9 Client and Server Communication  Clients and servers exchange messages in a request–response messaging pattern:  The client sends a request  The server returns a response.

10 Client and Server Communication  To communicate, the computers must have a common language, and they must follow rules so that both the client and the server know what to expect.  The language and rules of communication are defined in a communications protocol

11 Address  (leaving a lot of details that will be revealed in a dedicated networks course) TCP-IP is one such communication protocol.  An IP defines the address of a computer  in the form of 4, dot separated 8bit numbers, e.g. : 127.0.0.1  The address can be defined by the name of the machine, for example e-intro.cs.huji.ac.il  When we want to use our computer as the address we can use ‘localhost’ TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

12 Ports  A port is the endpoint of the communication.  It is always associated with the IP of a host (for example, server) and the communication protocol  Specific port numbers are often used to identify specific services  Port 80 = HTTP, 443 = HTTPS  Port 20 = FTP  Port 6881 = Bittorent TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

13 IP and Ports  We can say that the IP is the address is a building  If a letter is sent to this address without a specific apartment number, we cannot know which mailbox to put it in  So the IP is the building address and the port is the apartment number

14 IP, Ports and Sockets  The combination of an IP and a port defines a socket.  Sockets let us create a dedicated communication channel between two network entities. To\from this channel we can (similar to files syntax and terminology):  Write – to transfer information to the other side.  Read – to receive any information written to the channel by the other side. TCP-IP Illustrated Volume 1 The Protocols, W. Richard Stevens, 1994 Addison Wesley

15 Networks with Python  The socket module lets us create and manage network communication via Python.  Creating a new socket object: import socket my_socket = socket.socket()  Python’s socket object implement the general notion of network sockets and abstracts the “lower levels” of communication.

16 Networks with Python  For a full API see : https://docs.python.org/3/library/socket.ht ml https://docs.python.org/3/library/socket.ht ml  For a nice tutorial : https://docs.python.org/3/howto/sockets.h tml#socket-howto https://docs.python.org/3/howto/sockets.h tml#socket-howto

17 Client-server communication example Client Server

18 connect ing a socket - client  Connecting a socket requires the definition of:  Target address ( host ) : IP\host name.  Target port : should be identical between both sides.  The connect method gets one parameter of the address which is a tuple (IP, port)

19 connect ing a socket - client  Lets see an example: what happens when we enter this url : https://docs.python.org in our browser:https://docs.python.org address format is host and port number

20 Bind and listen: Server  Binding a socket = Declaring it is dedicated for a communication via a specific address.  listen : the dedicated communication channel (= the socket) will wait for client requests for connections.  If a connection is in progress and another request arrives, we put it in a queue. The queue size should be defined when we start to listen

21 Bind and listen: Server We could have replaced socket.gethostname() with ‘localhost’, but then it would be visible only within the same machine

22 accept from a socket - server  Accepting communication could only be from a bind ed socket.  When the socket receives a request it returns:  a new socket for sending and receiving data.  the address of the other side.

23 Type of Data  The type of data that is passed through the sockets is bytes.  We can encode any string we want as bytes.  Any information read from the port should be decoded from bytes to string.  Encoding : The process of translating characters to bytes\numbers.  Famous encoding methods : UTF8, ASCII

24  bytes : when creating a bytes object from string we should declare what encoding to use (example coding = utf8) : >> s = bytes('hi!','utf8') >> b‘hi!' # b stands for bytes >> s + 'bi' Traceback (most recent call last): File " ", line 1, in s + 'bi' TypeError: can't concat bytes to str Encoding String  Bytes

25  We decode using the same encoding method >> s = bytes('hi!',‘ascii') >> b'hi!' >> s.decode(‘ascii') >> 'hi!' Dcoding Bytes  String

26 Send Message  Send messages using the sendall method : my_socket.connect(address) my_socket.sendall(string_as_bytes)

27 Receive Message  Receive using the recv method.  Maximum amount of data to be received per single message is defined by BUFFER_SIZE. BUFFER_SIZE = 1024 msg = my_socket.recv(BUFFER_SIZE)

28 Receive Message  We may receive more than one message.  How do we know when one message ends and the other begins?  We must define a protocol between the server and the client that both must obey.

29 Receive Message  For example, we can say that each message must end by a special character, like ‘\n’  So when we read ‘\n’ we know that this is the end of a message and all the data that comes after belongs to a new message

30 Receive Message

31  But what if we received only the beginning of a message after one call of recv ?  We should get the rest of it in the next call, but we should keep the data we received in the previous call in a buffer

32 Receive Message

33 When recv returns 0 bytes, it means the other side has closed (or is in the process of closing) the connection But if the connection is not broken but there is no message to receive, we could wait forever…

34 Using Select We can call select.select(rlist, wlist, xlist, timeout) to see if any of the input sockets are ready.  rlist: wait until ready for reading  wlist: wait until ready for writing  xlist: wait for an “exceptional condition”  When the timeout argument is omitted the function blocks until at least socket is ready https://docs.python.org/3/library/select.html

35 Using Select  The return value is a triple of lists of objects that are ready: subsets of the first three arguments.  When the time-out is reached without a file descriptor becoming ready, three empty lists are returned. https://docs.python.org/3/library/select.html

36 Using Select – Client example s = socket.socket() s.connect((HOST, PORT)) # receiving data: while True: r,w,x = select.select([s], [], [], 5) for sock in r: if sock == s: data = r[0].recv(BUFF_SIZE) # do something with the data.. s.close() reading from our socket If there is no sockets to read we will not call recv and wait

37 close ing a socket  Same as files, when communication is terminated, the socket should be closed: my_socket.close()

38 GUI

39 Graphical User Interface  A GUI is a graphical (rather than purely textual) user interface to a computer  In the past interfaces to computers were not graphical, they were text-and-keyboard oriented  Today almost all operating systems, applications and programs we use consist of a GUI

40 GUI in Python  tkinter is the standard GUI library for Python  The GUI consist of the main window and different widgets within it

41 GUI in Python  To initialize Tkinter, we have to create a Tk root widget. This is an ordinary window, with a title bar and other decoration provided by your window manager.  You should only create one root widget for each program, and it must be created before any other widgets.  The root widget contains all other widgets

42 GUI in Python  After creating the main window and its contained widgets, the window will not appear until we will enter the event loop by calling mainloop() method on the main window  The program will stay in the event loop until we close the window.  It enables us to handle events from the user

43 GUI in Python  The window won’t appear until we’ve entered the Tkinter event loop (mainloop)  The program will stay in the event loop until we close the window.

44 Widgets  Widget is an element of interaction in a GUI, such as button or scroll bar  Tkinter provides the following widgets:  Button  Canvas  entry  Frame  Label  Menu  text  And many more.. http://www.python-course.eu/python_tkinter.php

45 Adding Widgets  All widgets are implemented in widgets classes, so each time we use a widget we create such object.  The first parameter in the constructor of a widget is its parent widget

46 Widget Geometry Managers:  After adding a widget, we need to call a geometry manager in order to display it  There are three special methods that we can use for doing that: grid, pack and place  Try not to use grid and pack on the same container

47 Widget pack() Method  pack() method of the widget object: widget.pack(pack_options)  This organizes widgets in blocks before placing them in the parent widget.  The pack method doesn’t really display the widget; it adds the widget to a list of widgets managed by the parent widget http://effbot.org/zone/tkinter-geometry.htm

48 Widget pack() options:  expand: When set to true, widget expands to fill any space not otherwise used in widget's parent.  fill: Determines whether widget fills any extra space allocated to it by the packer only horizontally, only vertically, both or none (defult)  side: Determines which side of the parent widget packs against: TOP (default), BOTTOM, LEFT, or RIGHT.

49 Adding Widgets - Label  The label is a widget that the user just views but not interact with.  A Label is a widget which is used to display text or an image.  We can set the text in the text argument in the Label constructor  More options: http://effbot.org/tkinterbook/label.htm

50 Adding Label Widget Here we used text and font options

51 The Button Widget  Buttons can contain text or images  Buttons can be associated with a function or a method that will be called after button click event  The association is by assigning command argument in the Button constructor to the function we wand to call

52 The Button Widget Assigning the function that will be called on click event

53 The Button Widget Clicking three times on the button:

54 The Canvas Widget  The Canvas widget provides structured graphics facilities  It can be used to draw graphs and plots, create graphics editors, and implement various kinds of custom widgets.  To display things on the canvas, you create one or more canvas items using create methods  The create method returns the item id

55 Canvas Items and their Create Methods  arc  image  line  oval  polygon  rectangle  text  window  create_arc  create_image  create_line  create_oval  create_polygon  create_rectangle  create_text  create_window

56 Canvas items  The window coordinates of the canvas start at the upper left corner (this is (0,0))  The create methods get the coordinates as arguments, separated by commas

57 Canvas Widget we set the color and the width of the line

58 Events and Bindings  When we run the mainloop(), we are actually in events loop  Events can come from various sources, including key presses and mouse operations by the user, and redraw events from the window manager  For each widget, we can bind Python functions and methods to events: widget.bind(event, handler)

59 Events and Bindings  If an event matching the event description occurs in the widget, the given handler is called with an object describing the event.  The event is an object, and the handler is a callback method that we can implement.

60 Some Events Formats ,,  A mouse button is pressed over the widget. Button 1 is the leftmost button, button 2 is the middle button (where available), and button 3 the rightmost button  The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.

61 Some Events Formats   The mouse is moved, with mouse button 1 being held down (use B2 for the middle button, B3 for the right button).  The current position of the mouse pointer is provided in the x and y members of the event object passed to the callback.  There are more events (mouse and keyboard): http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm

62 Events and Bindings - example Read about Frame widget: http://effbot.org/tkinterbook/frame.htm

63 The after Method after(delay_ms, callback=None, *args)  This is a widget method.  It registers a callback function that will be called after a given number of milliseconds.  Since for running the GUI we are in a loop (the mainloop()), we can use after to call a certain method over and over again

64 Using after example:

65 Protocols Handlers  The protocols refer to interaction between the application and the window manager.  One example is closing a window using the window manager (the built-in x button on the upper right)  Say we want to do something when the user closes the window  We can use the protocol WM_DELETE_WINDOW

66 Protocols Handlers  The protocol method, much like bind, receives the protocol name and the handler (the method) that should be called upon it

67 Protocols Handlers Lets close the window We want to call this method upon closing the window


Download ppt "INTRO2CS Tirgul 12 – Networks and GUI. Today:  Network and Communication  GUI - tkinter."

Similar presentations


Ads by Google