 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a.

Slides:



Advertisements
Similar presentations
CCNA – Network Fundamentals
Advertisements

C# - Files and Streams Outline Files and Streams Classes File and Directory Creating a Sequential-Access File Reading Data from a Sequential-Access.
1 L54 Networking (3). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
A CHAT CLIENT-SERVER MODULE IN JAVA BY MAHTAB M HUSSAIN MAYANK MOHAN ISE 582 FALL 2003 PROJECT.
User Datagram Protocol. Introduction UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive.
1 Java Networking – Part I CS , Spring 2008/9.
1 L52 Networking (1). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
CSCI 4550/8556 Computer Networks Comer, Chapter 3: Network Programming and Applications.
 Pearson Education, Inc. All rights reserved. 1 CH24 Networking : OBJECTIVES In this chapter you will learn:  To understand Java networking.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
 2006 Pearson Education, Inc. All rights reserved Networking: Streams-Based Sockets and Datagrams.
McGraw-Hill©The McGraw-Hill Companies, Inc., 2004 Application Layer PART VI.
© 2007 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.1 Computer Networks and Internets with Internet Applications, 4e By Douglas.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 26 Client Server Interaction Communication across a computer network requires a pair of application programs to cooperate. One application on one.
 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1 Introduction 22.2 Establishing.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Network Layer Programing Connection-Oriented Sockets SWE 344 Internet Protocols & Client Server Programming.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
Chapter 17 Networking Dave Bremer Otago Polytechnic, N.Z. ©2008, Prentice Hall Operating Systems: Internals and Design Principles, 6/E William Stallings.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
Lector: Aliyev H.U. Lecture №6 Design of client-server communication software. TCP-based network programming TASHKENT UNIVERSITY OF INFORMATION TECHNOLOGIES.
Windows Programming Using C# Internet Programming.
Jozef Goetz, Application Layer PART VI Jozef Goetz, Position of application layer The application layer enables the user, whether human.
Internet Applications and Network Programming Dr. Abraham Professor UTPA.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2 Base Classes and Derived.
Dr. John P. Abraham Professor University of Texas Pan American Internet Applications and Network Programming.
Multi-Client/Server GUI Application. Overview As part of the TCP.
Reference: Lecturer Lecturer Reham O. Al-Abdul Jabba lectures for cap211 Files and Streams- I.
Chapter 2 Applications and Layered Architectures Sockets.
The Socket Interface Chapter 21. Application Program Interface (API) Interface used between application programs and TCP/IP protocols Interface used between.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
UDP Client-Server. The Socket Class The Socket class provides a set of methods and properties for network communications. The Socket class allows you.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
12/5/2015.net 1 system.net Contains any network functionallity you would need in c# Several sub namespaces exists to allow for more fined control –System.Net.Sockets.
Networking OSI (Open Systems Interconnection) model of computer networking, seven layers (the Application, Presentation, Session, Transport, Network, Data.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Craps Game Application Introducing Random-Number Generation and Enum.
DOTSNBOXES. Overview Dots and Boxes is played originally with the use of paper, pen and 2 players. The Game board is a matrix of points and vary in size.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
1 Kyung Hee University Chapter 11 User Datagram Protocol.
Socket programming with UDP UDP: no “connection” between client & server sender explicitly attaches IP destination address and port # to each packet receiver.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Files and Streams. What is a file? Up until now, any stored data within a program is lost when the program closes. A file is a permanent way to store.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Files and Streams. Objectives Learn about the classes that support file input/output Understand the concept of abstraction and how it related to the file.
1 Network Communications A Brief Introduction. 2 Network Communications.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
1 K. Salah Application Layer Module K. Salah Network layer duties.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
The Echo Server Problem. Contents  Basic Networking Concepts  The Echo Server Problem.
Based on Deitel C# For Programmers ch 23
Chapter 11 – Exception Handling
A variable is a name for a value stored in memory.
Networking: Streams-Based Sockets and Datagrams
Internet Applications and Network Programming
.Net Sockets.
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Exceptions and networking
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2008
Presentation transcript:

 2002 Prentice Hall. All rights reserved. 1 Chapter 22 – Networking: Streams- Based Sockets and Datagrams Outline 22.1Introduction 22.2 Establishing a Simple Server (Using Stream Sockets) 22.3 Establishing a Simple Client (Using Stream Sockets) 22.4 Client/Server Interaction via Stream Socket Connections 22.5 Connectionless Client/Server Interaction via Datagrams 22.6 Client/Server Tic-Tac-Toe Using a Multithreaded Server

 2002 Prentice Hall. All rights reserved Introduction Client-server relationship –The client requests some actions to be performed; server performs the action and responds to the client System.Net.Sockets –Socket-based communications Enable developers to view networking as if it were file I/O Employ stream sockets –Stream Sockets provide a connection-oriented service like Transmission Control Protocol (TCP) –Sockets Sockets are fundamental way to perform network communication in the.NET Framework

 2002 Prentice Hall. All rights reserved Establishing a Simple Server (Using Stream Sockets) Step 1: Create an object of class TcpListener –TcpListener belongs to a namespace System.Net.Sockets –TcpListener assigns the server to port number (IP Address) Step 2: Call TcpListener’s Start method –Start method causes TcpListener object to begin listening for connection requests Step 3: Makes connection between server & client –Socket connection = Server.AcceptSocket( ) Step 4: Processing Phase Step 5: Connection Termination Phase

 2002 Prentice Hall. All rights reserved Establishing a Simple Client (Using Stream Sockets) Step 1: Create Object of class TcpClient –Method Connect of class TcpClient calls method Connect of class Socket to establish the connection Step 2: Uses GetStream to get NetworkStream –Methods WriteByte and Write can be used to output individual bytes or sets of bytes to the server Step 3: Processing phase –Client uses methods Read, ReadByte, Write, and WriteByte of class NetworkStream to perform communications Step 4: Close connection

 2002 Prentice Hall. All rights reserved Client/Server Interaction via Stream- Socket Connection Client/server chat application –Server waits for client’s request to make a connection –Both client and server applications contain Textboxes the enhance users to type messages and send them away –Message “TERMINATE” disconnects the connection between the client and the server

 2002 Prentice Hall. All rights reserved. Outline 6 Server.vb 1 ' Fig. 22.1: Server.vb 2 ' Set up a Server that receives connections from clients and sends 3 ' String data to clients. 4 5 Imports System.Windows.Forms 6 Imports System.Threading 7 Imports System.Net.Sockets 8 Imports System.IO 9 10 Public Class FrmServer 11 Inherits Form ' TextBoxes for receiving user input and displaying information 14 Friend WithEvents txtInput As TextBox 15 Friend WithEvents txtDisplay As TextBox Private connection As Socket ' Socket object handles connection 18 Private readThread As Thread ' server thread ' Stream through which to transfer data 21 Private socketStream As NetworkStream ' objects for writing and reading data 24 Private writer As BinaryWriter 25 Private reader As BinaryReader Public Sub New() 28 MyBase.New() ' equired by the Windows Form Designer. 31 InitializeComponent() ' add any initialization after the 34 ' InitializeComponent call 35

 2002 Prentice Hall. All rights reserved. Outline 7 Server.vb 36 ' create thread from server 37 readThread = New Thread(AddressOf RunServer) 38 readThread.Start() 39 End Sub ' New ' Visual Studio.NET generated code ' invoked when user closes server 44 Private Sub FrmServer_Closing( _ 45 ByVal sender As System.Object, _ 46 ByVal e As system.ComponentModel.CancelEventArgs) _ 47 Handles MyBase.Closing System.Environment.Exit(System.Environment.ExitCode) 50 End Sub ' FrmServer_Closing ' send server text to client 53 Private Sub txtInput_KeyDown( ByVal sender As System.Object, _ 54 ByVal e As system.Windows.Forms.KeyEventArgs) _ 55 Handles txtInput.KeyDown ' send text to client 58 Try ' send text if user pressed Enter and connection exists 61 If (e.KeyCode = Keys.Enter AndAlso _ 62 Not connection Is Nothing) Then writer.Write("SERVER>>> " & txtInput.Text) ' send data txtDisplay.Text &= vbCrLf & "SERVER>>> " & _ 67 txtInput.Text 68 Creates a Thread that accepts connections from clients Starts the Thread Reads the String and sends it via method write of class BinaryWriter Defines FrmServer_Closing event handler for the Closing event

 2002 Prentice Hall. All rights reserved. Outline 8 Server.vb 69 ' close connection if server’s user signals termination 70 If txtInput.Text = "TERMINATE" Then 71 connection.Close() 72 End If txtInput.Clear() 75 End If ' handle exception if error occurs when server sends data 78 Catch exception As SocketException 79 txtDisplay.Text &= vbCrLf & "Error writing object" End Try End Sub ' txtInput_KeyDown ' allow client to connect and display text sent by user 86 Public Sub RunServer() 87 Dim listener As TcpListener 88 Dim counter As Integer = ' wait for request, then establish connection 91 Try ' Step 1: create TcpListener 94 listener = New TcpListener(5000) ' Step 2: TcpListener waits for connection request 97 listener.Start() ' Step 3: establish connection upon client request 100 While True 101 txtDisplay.Text = "Waiting for connection" & vbCrLf 102 Declares TcpListener to listen for a connection request from a client at port 5000 Invokes method Start of TcpListener object Calls method Close of the Socket object to close the connection

 2002 Prentice Hall. All rights reserved. Outline 9 Server.vb 103 ' accept an incoming connection 104 connection = listener.AcceptSocket() ' create NetworkStream object associated with socket 107 socketStream = New NetworkStream(connection) ' create objects for transferring data across stream 110 writer = New BinaryWriter(socketStream) 111 reader = New BinaryReader(socketStream) txtDisplay.Text &= "Connection " & counter & _ 114 " received." & vbCrLf ' inform client that connection was successfull 117 writer.Write("SERVER>>> Connection successful") txtInput.ReadOnly = False 120 Dim theReply As String = "" ' Step 4: read String data sent from client 123 Try ' loop until client signals termination 126 Do 127 theReply = reader.ReadString() ' read data ' display message 130 txtDisplay.Text &= vbCrLf & theReply Loop While (theReply <> "CLIENT>>> TERMINATE" _ 133 AndAlso connection.Connected) ' handle exception if error reading data 136 Catch inputOutputException As IOException 137 MessageBox.Show("Client application closing") Calls method AcceptSocket of the TcpListener object Passes the Socket object as an argument to the constructor of a NetworkStream object Creates instances of BinaryWriter and BinaryReader classes Append text to the TextBox indicating that connection was received Do/Loop While executes until server receives termination message Uses BinaryReader method ReadSring to read a String from the stream

 2002 Prentice Hall. All rights reserved. Outline 10 Server.vb ' close connections 140 Finally txtDisplay.Text &= vbCrLf & _ 143 "User terminated connection" txtInput.ReadOnly = True ' Step 5: close connection 148 writer.Close() 149 reader.Close() 150 socketStream.Close() 151 connection.Close() counter += End Try End While ' handle exception if error occurs in establishing connection 159 Catch inputOutputException As IOException 160 MessageBox.Show("Server application closing") End Try End Sub ' RunServer End Class ' FrmServer Close the BinaryWriter, BinaryReader, NetworkStream and Socket

 2002 Prentice Hall. All rights reserved. Outline 11 Client.vb 1 ' Fig. 22.2: Client.vb 2 ' Set up a client that reads and displays data sent from server. 3 4 Imports System.Windows.Forms 5 Imports System.Threading 6 Imports System.Net.Sockets 7 Imports System.IO 8 9 Public Class FrmClient 10 Inherits Form ' TextBoxes for inputting and displaying information 13 Friend WithEvents txtInput As TextBox 14 Friend WithEvents txtDisplay As TextBox ' stream for sending data to server 17 Private output As NetworkStream ' objects for writing and reading bytes to streams 20 Private writer As BinaryWriter 21 Private reader As BinaryReader Private message As String = "" ' message sent to server ' thread prevents client from blocking data transfer 26 Private readThread As Thread Public Sub New() 29 MyBase.New() ' equired by the Windows Form Designer. 32 InitializeComponent() ' add any initialization after the 35 ' InitializeComponent call

 2002 Prentice Hall. All rights reserved. Outline 12 Client.vb readThread = New Thread(AddressOf RunClient) 38 readThread.Start() 39 End Sub ' New ' Visual Studio.NET generated code ' invoked when user closes application 44 Private Sub FrmClient_Closing(ByVal sender As System.Object, _ 45 ByVal e As System.ComponentModel.CancelEventArgs) _ 46 Handles MyBase.Closing System.Environment.Exit(System.Environment.ExitCode) 49 End Sub ' send user input to server 52 Private Sub txtInput_KeyDown(ByVal sender As System.Object, _ 53 ByVal e As System.windows.Forms.KeyEventArgs) _ 54 Handles txtInput.KeyDown ' send user input if user pressed Enter 57 Try ' determine whether user pressed Enter 60 If e.KeyCode = Keys.Enter Then ' send data to server 63 writer.Write("CLIENT>>> " & txtInput.Text) txtDisplay.Text &= vbCrLf & "CLIENT>>> " & _ 66 txtInput.Text txtInput.Clear() 69 End If 70 The client object creates a Thread in its constructor to handle all incoming messages The event handler txtInput_KeyDown reads the String from the TextBox and sends it via BinaryWriter method Write

 2002 Prentice Hall. All rights reserved. Outline 13 Client.vb 71 ' handle exception if error occurs in sending data to server 72 Catch exception As SocketException 73 txtDisplay.Text &= vbCrLf & "Error writing object" 74 End Try End Sub ' txtInput_KeyDown ' connect to server and display server-generated text 79 Public Sub RunClient() 80 Dim client As TcpClient ' instantiate TcpClient for sending data to server 83 Try txtDisplay.Text &= "Attempting connection" & vbCrLf ' Step 1: create TcpClient and connect to server 88 client = New TcpClient() 89 client.Connect("localhost", 5000) ' Step 2: get NetworkStream associated with TcpClient 92 output = client.GetStream() ' create objects for writing and reading across stream 95 writer = New BinaryWriter(output) 96 reader = New BinaryReader(output) txtDisplay.Text &= vbCrLf & "Got I/O streams" & vbCrLf txtInput.ReadOnly = False ' Step 3: processing phase 103 Try 104 Method RunClient connects, receives and sends data to and from the Server Declares TcpClient object Invokes method Connect to establish connection The client obtains NetworkStream through a call to TcpClient method GetStream

 2002 Prentice Hall. All rights reserved. Outline 14 Client.vb 105 ' loop until server signals termination 106 Do ' read message from server 109 message = reader.ReadString 110 txtDisplay.Text &= vbCrLf & message Loop While message <> "SERVER>>> TERMINATE" ' handle exception if error in reading server data 115 Catch inputOutputException As IOException 116 MessageBox.Show("Client application closing") ' Step 4: close connection 119 Finally txtDisplay.Text &= vbCrLf & "Closing connection." & _ 122 vbCrLf writer.Close() 125 reader.Close() 126 output.Close() 127 client.Close() End Try Application.Exit() ' handle exception if error in establishing connection 134 Catch inputOutputException As Exception 135 MessageBox.Show("Client application closing") End Try 138 Do/Loop While executes until server receives termination message Uses BinaryReader method ReadString to obtain the next message from the server Displays the message “Closing connection” Close BinaryWriter, BinaryReader, NetworkStream and TcpClient objects

 2002 Prentice Hall. All rights reserved. Outline 15 Client.vb 139 End Sub ' RunClient End Class ' FrmClient

 2002 Prentice Hall. All rights reserved. Outline 16 Client.vb

 2002 Prentice Hall. All rights reserved. Outline 17 Client.vb

 2002 Prentice Hall. All rights reserved Connectionless Client/Server Interaction via Datagrams Connectionless Transmission via Datagrams –Bundles and sends information via datagrams Information is broken into several pieces if it is too big Information might arrive in order, out of order or not at all

 2002 Prentice Hall. All rights reserved. Outline 19 Server.vb 1 ' Fig. 22.3: Server.vb 2 ' Server receives packets from a client, then echoes packets back 3 ' to clients. 4 5 Imports System.Windows.Forms 6 Imports System.Net 7 Imports System.Net.Sockets 8 Imports System.Threading 9 10 Public Class FrmDatagramServer 11 Inherits Form ' TextBox displays packet information 14 Friend WithEvents txtDisplay As TextBox ' reference to client that will send packet information 17 Private client As UdpClient ' client IP address/port number pair 20 Private receivePoint As IPEndPoint Public Sub New() 23 MyBase.New() ' equired by the Windows Form Designer. 26 InitializeComponent() ' add any initialization after the 29 ' InitializeComponent call ' instantiate UdpClient listening for requests at port client = New UdpClient(5000) ' hold IP address and port number of client 35 receivePoint = New IPEndPoint(New IPAddress(0), 0) Creates an instance of the UdpClient class that receives data at port 5000 Creates an instance of class IPEndPoint to hold IP address and port number of client(s) that transmit to Server

 2002 Prentice Hall. All rights reserved. Outline 20 Server.vb Dim readThread As Thread = New Thread _ 38 (New ThreadStart(AddressOf WaitForPackets)) readThread.Start() ' wait for packets 41 End Sub ' New ' Visual Studio.NET generated code ' invoked when user closes server 46 Protected Sub Server_Closing(ByVal sender As system.Object, _ 47 ByVal e As System.ComponentModel.CancelEventArgs) _ 48 Handles MyBase.Closing System.Environment.Exit(System.Environment.ExitCode) 51 End Sub ' Server_Closing ' wait for packets to arrive from client 54 Public Sub WaitForPackets() ' use infinite loop to wait for data to arrive 57 While True ' receive byte array from client 60 Dim data As Byte() = client.Receive(receivePoint) ' output packet data to TextBox 63 txtDisplay.Text &= vbCrLf & "Packet received:" & _ 64 vbCrLf & "Length: " & data.Length & vbCrLf & _ 65 "Containing: " & _ 66 System.Text.Encoding.ASCII.GetString(data) txtDisplay.Text &= vbCrLf & vbCrLf & _ 69 "Echo data back to client..." 70 Method Receive receives a byte array from the client Update the Server’s display to include the packet’s information and content

 2002 Prentice Hall. All rights reserved. Outline 21 Server.vb 71 ' echo information from packet back to client 72 client.Send(data, data.Length, receivePoint) 73 txtDisplay.Text &= vbCrLf & "Packet sent" & _ 74 vbCrLf End While End Sub ' WaitForPackets End Class ' FrmDatragramServer Echoes the data back to the client using UdpClient method Send

 2002 Prentice Hall. All rights reserved. Outline 22 Client.vb 1 ' Fig. 22.4: Client.vb 2 ' Client sends packets to, and receives packets from, a server. 3 4 Imports System.Windows.Forms 5 Imports System.Net 6 Imports System.Net.Sockets 7 Imports System.Threading 8 9 Public Class FrmDatagramClient 10 Inherits Form ' TextBoxes for inputting and displaying packet information 13 Friend WithEvents txtInput As TextBox 14 Friend WithEvents txtDisplay As TextBox ' UdpClient that sends packets to server 17 Private client As UdpClient ' hold IP address and port number of clients 20 Private receivePoint As IPEndPoint Public Sub New() 23 MyBase.New() ' equired by the Windows Form Designer. 26 InitializeComponent() ' add any initialization after the 29 ' InitializeComponent() call receivePoint = New IPEndPoint(New IPAddress(0), 0) ' instantiate UdpClient to listen on port client = New UdpClient(5001) 35 Declares UdpClient object to receive packets at the port 5001

 2002 Prentice Hall. All rights reserved. Outline 23 Client.vb 36 Dim thread As Thread = New Thread _ 37 (New ThreadStart(AddressOf WaitForPackets)) thread.Start() ' wait for packets 40 End Sub ' New ' Visual Studio.NET generated code ' invoked when user closes client 45 Private Sub FrmDatagramClient_Closing( _ 46 ByVal sender As System.Object, _ 47 ByVal e As System.ComponentModel.CancelEventArgs) _ 48 Handles MyBase.Closing System.Environment.Exit(System.Environment.ExitCode) 51 End Sub ' FrmDatagramClient_Closing ' invoked when user presses key 54 Private Sub txtInput_KeyDown( ByVal sender As System.Object, _ 55 ByVal e As System.Windows.Forms.KeyEventArgs) _ 56 Handles txtInput.KeyDown ' determine whether user pressed Enter 59 If e.KeyCode = Keys.Enter Then ' create packet (datagram) as String 62 Dim packet As String = txtInput.Text txtDisplay.Text &= vbCrLf & _ 65 "Sending packet containing: " & packet ' convert packet to byte array 68 Dim data As Byte() = _ 69 System.Text.Encoding.ASCII.GetBytes(packet) 70 Convert the String that the user entered in the TextBox to Byte array

 2002 Prentice Hall. All rights reserved. Outline 24 Client.vb 71 ' send packet to server on port client.Send(data, data.Length, "localhost", 5000) txtDisplay.Text &= vbCrLf & "Packet sent" & vbCrLf 75 txtInput.Clear() 76 End If End Sub ' txtInput_KeyDown ' wait for packets to arrive 81 Public Sub WaitForPackets() While True ' receive byte array from client 86 Dim data As Byte() = client.Receive(receivePoint) ' output packet data to TextBox 89 txtDisplay.Text &= vbCrLf & "Packet received:" & _ 90 vbCrLf & "Length: " & data.Length & vbCrLf & _ 91 System.Text.Encoding.ASCII.GetString(data) End While End Sub ' WaitForPackets End Class ' FrmDatagramClient Invokes UdpClient method Send to send the Byte array to the Server that is located on the localhost Uses an infinite loop to wait for these packets UdpClient method Receive blocks until a packet of data is received Displays the message in the TextBox “packet received” when packet arrives

 2002 Prentice Hall. All rights reserved. Outline 25 Client.vb

 2002 Prentice Hall. All rights reserved Client/Server Tic-Tac-Toe Using a Multithreaded Server Stream Sockets and Client/Server Techniques –FrmServer allows the FrmClients to connect to server and play Tic-Tac-Toe –Throughout the game, the server maintains information regarding the status of the board so that the server can validate players requested moves –Neither the player nor the client can establish whether a payer has won the game

 2002 Prentice Hall. All rights reserved. Outline 27 Server.vb 1 ' Fig. 22.5: Server.vb 2 ' Server maintains a Tic-Tac-Toe game for two client applications. 3 4 Imports System.Windows.Forms 5 Imports System.Net.Sockets 6 Imports System.Threading 7 8 Public Class FrmServer 9 Inherits Form ' TextBox for displaying results 12 Friend WithEvents txtDisplay As TextBox Private board As Char() ' Tic-Tac-Toe game board Private players As CPlayer() ' player-client applications 17 Private playerThreads As Thread() ' Threads that run clients ' indicates current player ("X" or "O") 20 Private currentPlayer As Integer ' indicates whether server has disconnected 23 Private disconnect As Boolean = False Public Sub New() 26 MyBase.New() ' required by the Windows Form Designer 29 InitializeComponent() ' add any initialization after the 32 ' InitializeComponent call board = New Char(8) {} ' create board with nine squares 35 Creates a Char array to store the moves players made

 2002 Prentice Hall. All rights reserved. Outline 28 Server.vb 36 players = New CPlayer(1) {} ' create two players ' create one thread for each player 39 playerThreads = New Thread(1) {} 40 currentPlayer = ' use separate thread to accept connections 43 Dim getPlayers As Thread = New Thread(New ThreadStart( _ 44 AddressOf SetUp)) getPlayers.Start() 47 End Sub ' New ' Visual Studio.NET generated code ' invoked when user closes server window 52 Private Sub FrmServer_Closing(ByVal sender As System.Object, _ 53 ByVal e As System.ComponentModel.CancelEventArgs) _ 54 Handles MyBase.Closing disconnect = True 57 End Sub ' FrmServer_Closing ' accept connections from two client applications 60 Public Sub SetUp() ' server listens for requests on port Dim listener As TcpListener = New TcpListener(5000) 64 listener.Start() ' accept first client (player) and start its thread 67 players(0) = New CPlayer(listener.AcceptSocket(), Me, "X"c) 68 playerThreads(0) = _ 69 New Thread(New ThreadStart(AddressOf players(0).Run)) 70 Creates an array of two references to CPlayer objects Creates an array of two references to Thread objects Creates and starts Thread getPlayers which |the FrmServer uses to accept connections so that current Thread does not block while awaiting players Thread getPlayers executes method Setup Creates a TcpListener object to listen for requests on port 5000

 2002 Prentice Hall. All rights reserved. Outline 29 Server.vb 71 playerThreads(0).Start() ' accept second client (player) and start its thread 74 players(1) = New CPlayer(listener.AcceptSocket, Me, "O"c) 75 playerThreads(1) = _ 76 New Thread(New ThreadStart(AddressOf players(1).Run)) playerThreads(1).Start() ' inform first player of other player’s connection to server 81 SyncLock (players(0)) players(0).threadSuspended = False 84 Monitor.Pulse(players(0)) 85 End SyncLock End Sub ' SetUp ' display message argument in txtDisplay 90 Public Sub Display(ByVal message As String) 91 txtDisplay.Text &= message & vbCrLf 92 End Sub ' Display ' determine whether move is valid 95 Public Function ValidMove(ByVal location As Integer, _ 96 ByVal player As Char) As Boolean ' prevent other threads from making moves 99 SyncLock(Me) Dim playerNumber As Integer = Create two Threads that execute and Run methods of each CPlayer object Sets the CPlayer’s threadSuspended variable to False Sends message to client indicating whether the move was valid

 2002 Prentice Hall. All rights reserved. Outline 30 Server.vb 103 ' playerNumber = 0 if player = "X", else playerNumber = If player = "O"c 105 playerNumber = End If ' wait while not current player's turn 109 While playerNumber <> currentPlayer 110 Monitor.Wait(Me) 111 End While ' determine whether desired square is occupied 114 If Not IsOccupied(location) Then ' place either an "X" or an "O" on board 117 If currentPlayer = 0 Then 118 board(location) = "X"c 119 Else 120 board(location) = "O"c 121 End If ' set currentPlayer as other player (change turns) 124 currentPlayer = (currentPlayer + 1) Mod ' notify other player of move 127 players(currentPlayer).OtherPlayerMoved(location) ' alert other player to move 130 Monitor.Pulse(Me) Return True 133 Else 134 Return False 135 End If End SyncLock Invokes the Pulse method so the waiting CPlayer can validate a move

 2002 Prentice Hall. All rights reserved. Outline 31 Server.vb End Function ' ValidMove ' determine whether specified square is occupied 142 Public Function IsOccupied(ByVal location As Integer) _ 143 As Boolean ' return True if board location contains "X" or "O" 146 If (board(location) = "X"c OrElse _ 147 board(location) = "O"c) Then Return True 150 Else 151 Return False 152 End If End Function ' IsOccupied ' allow clients to see if server has disconnected 157 Public ReadOnly Property Disconnected() As Boolean Get 160 Return disconnect 161 End Get End Property ' Disconnected ' determine whether game is over 166 Public Function GameOver() As Boolean ' place code here to test for winner of game 169 Return False 170 End Function ' GameOver End Class ' FrmServer

 2002 Prentice Hall. All rights reserved. Outline 32 Player.vb 1 ' Fig. 22.6: Player.vb 2 ' Represents a Tic-Tac-Toe player. 3 4 Imports System.Threading 5 Imports System.Net.Sockets 6 Imports System.IO 7 8 Public Class CPlayer 9 10 Private connection As Socket ' connection to server 11 Private server As FrmServer ' reference to Tic-Tac-Toe server ' object for sending data to server 14 Private socketStream As NetworkStream ' objects for writing and reading bytes to streams 17 Private writer As BinaryWriter 18 Private reader As BinaryReader Private mark As Char ' "X" or "O" 21 Friend threadSuspended As Boolean = True Sub New(ByVal socketValue As Socket, _ 24 ByVal serverValue As FrmServer, ByVal markValue As Char) ' assign argument values to class-member values 27 connection = socketValue 28 server = serverValue 29 mark = markValue ' use Socket to create NetworkStream object 32 socketStream = New NetworkStream(connection) 33 CPlayer constructor takes Socket object, FrmServer object and Char as three arguments

 2002 Prentice Hall. All rights reserved. Outline 33 Player.vb 34 ' create objects for writing and reading bytes across streams 35 writer = New BinaryWriter(socketStream) 36 reader = New BinaryReader(socketStream) 37 End Sub ' New ' inform other player that move was made 40 Public Sub OtherPlayerMoved(ByVal location As Integer) ' notify opponent 43 writer.Write("Opponent moved") 44 writer.Write(location) 45 End Sub ' OtherPlayerMoved ' inform server of move and receive move from other player 48 Public Sub Run() Dim done As Boolean = False ' indicates whether game is over ' indicate successful connection and send mark to server 53 If mark = "X"c Then 54 server.Display("Player X connected") 55 writer.Write(mark) 56 writer.Write("Player X connected" & vbCrLf) 57 Else 58 server.Display("Player O connected") 59 writer.Write(mark) 60 writer.Write("Player O connected, please wait" & vbCrLf) 61 End If ' wait for other player to connect 64 If mark = "X"c Then 65 writer.Write("Waiting for another player") 66 FrmServer calls method RunNotify the server of successful connection

 2002 Prentice Hall. All rights reserved. Outline 34 Player.vb 67 ' wait for notification that other player has connected 68 SyncLock (Me) While ThreadSuspended 71 Monitor.Wait(Me) 72 End While End SyncLock writer.Write("Other player connected. Your move") 77 End If ' play game 80 While Not done ' wait for data to become available 83 While connection.Available = 0 84 Thread.Sleep(1000) ' end loop if server disconnects 87 If server.Disconnected Then 88 Return 89 End If End While ' receive other player's move 94 Dim location As Integer = reader.ReadInt32() ' determine whether move is valid 97 If server.ValidMove(location, mark) Then ' display move on server 100 server.Display("loc: " & location) 101 Defines the While loop that suspends CPlayer “X” Thread until the server signals that CPlayer “O” has connected Executes the While structure enabling the user to play the game Property Disconnected checks whether server variable disconnect is True Calls method ReadInt32 of the BinaryReader object Passes the integer to server method ValidMove

 2002 Prentice Hall. All rights reserved. Outline 35 Player.vb 102 ' notify server of valid move 103 writer.Write("Valid move.") Else ' notify server of invalid move 106 writer.Write("Invalid move, try again") 107 End If ' exit loop if game over 110 If server.GameOver Then 111 done = True 112 End If End While ' close all connections 117 writer.Close() 118 reader.Close() 119 socketStream.Close() 120 connection.Close() 121 End Sub ' Run End Class ' CPlayer

 2002 Prentice Hall. All rights reserved. Outline 36 Client.vb 1 ' Fig. 22.7: Client.vb 2 ' Client for the Tic-Tac-Toe program. 3 4 Imports System.Windows.Forms 5 Imports System.Net.Sockets 6 Imports System.Threading 7 Imports System.IO 8 9 Public Class FrmClient 10 Inherits Form ' board contains nine panels where user can place "X" or "O" 13 Friend WithEvents Panel1 As Panel 14 Friend WithEvents Panel2 As Panel 15 Friend WithEvents Panel3 As Panel 16 Friend WithEvents Panel4 As Panel 17 Friend WithEvents Panel5 As Panel 18 Friend WithEvents Panel6 As Panel 19 Friend WithEvents Panel7 As Panel 20 Friend WithEvents Panel8 As Panel 21 Friend WithEvents Panel9 As Panel ' TextBox displays game status and other player's moves 24 Friend WithEvents txtDisplay As TextBox 25 Friend WithEvents lblId As Label ' Label displays player Private board As CSquare(,) ' Tic-Tac-Toe board ' square that user previously clicked 30 Private mCurrentSquare As CSquare Private connection As TcpClient ' connection to server 33 Private stream As NetworkStream ' stream to tranfser data 34

 2002 Prentice Hall. All rights reserved. Outline 37 Client.vb 35 ' objects for writing and reader bytes to streams 36 Private writer As BinaryWriter 37 Private reader As BinaryReader Private mark As Char ' "X" or "O" 40 Private turn As Boolean ' indicates which player should move Private brush As SolidBrush ' brush for painting board Private done As Boolean = False ' indicates whether game is over Public Sub New() 47 MyBase.New() ' required by the Windows Form Designer 50 InitializeComponent() ' add any initialization after the 53 ' InitializeComponent call board = New CSquare(2, 2) {} ' create 3 x 3 board ' create nine CSquare's and place their Panels on board 58 board(0, 0) = New CSquare(Panel1, " "c, 0) 59 board(0, 1) = New CSquare(Panel2, " "c, 1) 60 board(0, 2) = New CSquare(Panel3, " "c, 2) 61 board(1, 0) = New CSquare(Panel4, " "c, 3) 62 board(1, 1) = New CSquare(Panel5, " "c, 4) 63 board(1, 2) = New CSquare(Panel6, " "c, 5) 64 board(2, 0) = New CSquare(Panel7, " "c, 6) 65 board(2, 1) = New CSquare(Panel8, " "c, 7) 66 board(2, 2) = New CSquare(Panel9, " "c, 8) ' create SolidBrush for writing on Squares 69 brush = New SolidBrush(Color.Black) The FrmClient’s constructor

 2002 Prentice Hall. All rights reserved. Outline 38 Client.vb ' make connection request to server at port connection = New TcpClient("localhost", 5000) 73 stream = connection.GetStream() ' create objects for writing and reading bytes to streams 76 writer = New BinaryWriter(stream) 77 reader = New BinaryReader(stream) ' create thread for sending and receiving messages 80 Dim outputThread As Thread = New Thread(AddressOf Run) 81 outputThread.Start() 82 End Sub ' New ' Visual Studio.NET generated code ' invoked on screen redraw 87 Private Sub FrmClient_Paint(ByVal sender As System.Object, _ 88 ByVal e As System.Windows.Forms.PaintEventArgs) _ 89 Handles MyBase.Paint PaintSquares() 92 End Sub ' invoked when user closes client application 95 Private Sub FrmClient_Closing(ByVal sender As System.Object, _ 96 ByVal e As System.ComponentModel.CancelEventArgs) _ 97 Handles MyBase.Closing done = True 100 End Sub ' redraw Tic-Tac-Toe board 103 Public Sub PaintSquares() 104 Dim graphics As Graphics Opens a connection to the server and obtains a reference to the connection associated NetworkStream object from TcpClient

 2002 Prentice Hall. All rights reserved. Outline 39 Client.vb ' counters for traversing Tic-Tac-Toe board 107 Dim row As Integer 108 Dim column As Integer ' draw appropriate mark on each panel 111 For row = 0 To For column = 0 To ' get Graphics for each Panel 116 graphics = board(row, column).Panel.CreateGraphics() ' draw appropriate letter on panel 119 graphics.DrawString(board(row, _ 120 column).Mark.ToString(), Me.Font, brush, 8, 8) 121 Next 122 Next End Sub ' PaintSquares ' invoked when user clicks Panels 127 Private Sub square_MouseUp(ByVal sender As System.Object, _ 128 ByVal e As System.Windows.Forms.MouseEventArgs) Handles _ 129 Panel1.MouseUp, Panel2.MouseUp, Panel3.MouseUp, _ 130 Panel4.MouseUp, Panel5.MouseUp, Panel6.MouseUp, _ 131 Panel7.MouseUp, Panel8.MouseUp, Panel9.MouseUp ' counters for traversing Tic-Tac-Toe board 134 Dim row As Integer 135 Dim column As Integer For row = 0 To 2 138

 2002 Prentice Hall. All rights reserved. Outline 40 Client.vb 139 For column = 0 To ' determine which Panel was clicked 142 If board(row, column).Panel Is sender Then 143 mCurrentSquare = board(row, column) ' send move to server 146 SendClickedSquare(board(row, column).Location) 147 End If Next 150 Next End Sub ' square_MouseUp ' continuously update TextBox display 155 Public Sub Run() Dim quote As Char = ChrW(34) ' single quote ' get player's mark ("X" or "O") 160 mark = Convert.ToChar(stream.ReadByte()) 161 lblId.Text = "You are player " & quote & mark & quote ' determine which player's should move 164 If mark = "X" Then 165 turn = True 166 Else 167 turn = False 168 End If ' process incoming messages 171 Try 172

 2002 Prentice Hall. All rights reserved. Outline 41 Client.vb 173 ' receive messages sent to client 174 While True 175 ProcessMessage(reader.ReadString()) 176 End While ' notify user if server closes connection 179 Catch exception As EndOfStreamException 180 txtDisplay.Text = "Server closed connection. Game over." End Try End Sub ' Run ' process messages sent to client 187 Public Sub ProcessMessage(ByVal messageValue As String) ' if valid move, set mark to clicked square 190 If messageValue = "Valid move." Then 191 txtDisplay.Text &= "Valid move, please wait." & vbCrLf 192 mCurrentSquare.Mark = mark 193 PaintSquares() ' if invalid move, inform user to try again 196 ElseIf messageValue = "Invalid move, try again" Then 197 txtDisplay.Text &= messageValue & vbCrLf 198 turn = True ' if opponent moved, mark opposite mark on square 201 ElseIf messageValue = "Opponent moved" Then ' find location of opponent's move 204 Dim location As Integer = reader.ReadInt32() 205 Indicates if the move is validIndicates if the move is invalid Indicates if the opponent made a move Reads form the server an Integer specifying where on the board the client should place the opponent’s mark

 2002 Prentice Hall. All rights reserved. Outline 42 Client.vb 206 ' mark that square with opponent's mark 207 If mark = "X" Then 208 board(location \ 3, location Mod 3).Mark = "O"c 209 Else 210 board(location \ 3, location Mod 3).Mark = "X"c 211 End If PaintSquares() txtDisplay.Text &= "Opponent moved. Your turn." & vbCrLf turn = True ' change turns ' display message as default case 220 Else 221 txtDisplay.Text &= messageValue & vbCrLf 222 End If End Sub ' ProcessMessage ' send square position to server 227 Public Sub SendClickedSquare(ByVal location As Integer) ' send location to the server if current turn 230 If turn Then 231 writer.Write(location) 232 turn = False ' change turns 233 End If End Sub ' SendClickedSquare ' Property CurrentSquare 238 Public WriteOnly Property CurrentSquare() As CSquare 239

 2002 Prentice Hall. All rights reserved. Outline 43 Client.vb 240 Set(ByVal Value As CSquare) 241 mCurrentSquare = Value 242 End Set End Property ' CurrentSquare End Class ' FrmClient

 2002 Prentice Hall. All rights reserved. Outline 44 Client.vb

 2002 Prentice Hall. All rights reserved. Outline 45 Client.vb

 2002 Prentice Hall. All rights reserved. Outline 46 Square.vb 1 ' Fig. 22.8: Square.vb 2 ' Represents a square on the Tic-Tac-Toe board. 3 4 Public Class CSquare 5 6 Private squarePanel As Panel ' panel on which user clicks 7 Private squareMark As Char ' "X" or "O" 8 Private squareLocation As Integer ' position on board 9 10 ' constructor assigns argument values to class-member values 11 Public Sub New(ByVal panelValue As Panel, _ 12 ByVal markValue As Char, ByVal locationValue As Integer) squarePanel = panelValue 15 squareMark = markValue 16 squareLocation = locationValue 17 End Sub ' New ' return panel on which user can click 20 Public ReadOnly Property Panel() As Panel Get 23 Return squarePanel 24 End Get End Property ' Panel ' set and get squareMark ("X" or "O") 29 Public Property Mark() As Char Get 32 Return squareMark 33 End Get 34

 2002 Prentice Hall. All rights reserved. Outline 47 Square.vb 35 Set(ByVal Value As Char) 36 squareMark = Value 37 End Set End Property ' Mark ' return squarePanel position on Tic-Tac-Toe board 42 Public ReadOnly Property Location() As Integer Get 45 Return squareLocation 46 End Get End Property ' Location End Class ' CSquare